In this short tutorial, you'll see how to get the current year and month in Python using the datetime module. Whether you're generating monthly reports, creating timestamped filenames, or building calendar applications, extracting the current year and month is a fundamental task in date handling and time-based operations.

Python's datetime.now() method provides instant access to current date and time, from which you can extract year, month, day, and other components for various applications.

1. Getting Current Year and Month with datetime.now()

The datetime.now() method is the most straightforward way to get current year and month values as integers.

from datetime import datetime

now = datetime.now()

print(f"Current year: {now.year}")
print(f"Current month: {now.month}")
print(f"Current day: {now.day}")
print(f"Full date: {now.strftime('%Y-%m-%d')}")

Output Result:

Current year: 2026
Current month: 2
Current day: 14
Full date: 2026-02-14

How it works: The datetime.now() creates a datetime object representing the current moment. You can access year and month as integer attributes, perfect for calculations, comparisons, or formatting.

2. Formatting Year and Month for File Names and Reports

For file organization, report generation, and logging, you often need formatted date strings rather than raw integers.

from datetime import datetime

now = datetime.now()

monthly_report = f"sales_report_{now.year}_{now.month:02d}.pdf"
year_month = now.strftime('%Y-%m')
readable_format = now.strftime('%B %Y')
compact_format = now.strftime('%y%m')

print(f"Report filename: {monthly_report}")
print(f"ISO format: {year_month}")
print(f"Readable format: {readable_format}")
print(f"Compact format: {compact_format}")

Output Result:

Report filename: sales_report_2026_02.pdf
ISO format: 2026-02
Readable format: February 2026
Compact format: 2602

Real-world applications: The {now.month:02d} formatting ensures zero-padded months (01, 02, etc.), crucial for alphabetical sorting of files. The strftime() method offers flexible date formatting for different contexts.

3. Creating Date-Based Directory Structures

When organizing logs, backups, or archived data, creating year/month directory structures keeps files organized and easily searchable.

from datetime import datetime
from pathlib import Path

now = datetime.now()

archive_path = Path(f"backups/{now.year}/{now.month:02d}")
log_file = Path(f"logs/{now.year}/{now.month:02d}/app_{now.day:02d}.log")
invoice_dir = Path(f"invoices/{now.year}/Q{(now.month-1)//3 + 1}/{now.month:02d}")

print(f"Archive path: {archive_path}")
print(f"Log file: {log_file}")
print(f"Invoice directory: {invoice_dir}")

archive_path.mkdir(parents=True, exist_ok=True)
print(f"\nCreated: {archive_path}")

Output Result:

Archive path: backups/2026/02
Log file: logs/2026/02/app_14.log
Invoice directory: invoices/2026/Q1/02

Created: backups/2026/02

Production pattern: This hierarchical structure makes it easy to find files by date, archive old data, and implement retention policies. The parents=True creates all intermediate directories automatically.

4. Comparing Dates and Filtering by Year/Month

For data filtering, subscription management, or analytics, you often need to check if records match the current month or current year.

from datetime import datetime

current_year = datetime.now().year
current_month = datetime.now().month

transactions = [
    {'date': datetime(2026, 2, 10), 'customer': 'Amazon', 'amount': 15000},
    {'date': datetime(2026, 1, 25), 'customer': 'Google', 'amount': 22000},
    {'date': datetime(2025, 12, 15), 'customer': 'Microsoft', 'amount': 18000},
    {'date': datetime(2026, 2, 14), 'customer': 'Apple', 'amount': 25000}
]

this_month = [t for t in transactions 
              if t['date'].year == current_year and t['date'].month == current_month]

this_year = [t for t in transactions if t['date'].year == current_year]

print(f"This month transactions: {len(this_month)}")
print(f"This year transactions: {len(this_year)}")
print(f"This month revenue: ${sum(t['amount'] for t in this_month):,}")

Output Result:

This month transactions: 2
This year transactions: 3
This month revenue: $40,000

Business use case: This is essential for monthly KPI dashboards, revenue reporting, subscription renewals, and billing systems that need to isolate current period data.

Common Use Cases

Monthly Report Generation: Create reports with current month in title

report_name = f"Q{(now.month-1)//3 + 1}_Report_{now.year}.xlsx"

Subscription Expiry Checks: Validate if subscription is current

is_current = (sub_year == now.year and sub_month >= now.month)

Log File Rotation: Create monthly log files

log_file = f"app_{now.year}_{now.month:02d}.log"

Archive Management: Move files older than current month to archive

if file_date.year < now.year or file_date.month < now.month:
    archive_file(file)

Birthday/Anniversary Reminders: Check if event is this month

if event.month == now.month and event.day >= now.day:
    send_reminder()

Date Format Codes Reference

Code Output Example
%Y 4-digit year 2026
%y 2-digit year 26
%m Month number (01-12) 02
%B Full month name February
%b Short month name Feb
%d Day of month 14
%Y-%m ISO year-month 2026-02

Alternative Methods

Using date.today() for date-only operations:

from datetime import date

today = date.today()
print(f"Year: {today.year}, Month: {today.month}")

Output Result:

Year: 2026, Month: 2

Getting month name directly:

import calendar

month_name = calendar.month_name[datetime.now().month]
print(f"Current month: {month_name}")

Output Result:

Current month: February

Common Pitfalls

Forgetting zero-padding for months:

wrong = f"{now.year}-{now.month}"
correct = f"{now.year}-{now.month:02d}"

Using 1-indexed months incorrectly:

quarter = (now.month - 1) // 3 + 1

Time zone issues:

from datetime import datetime, timezone
utc_now = datetime.now(timezone.utc)

Choosing the Right Method

  • Need integers for calculations? → Use .year and .month attributes (Method 1)
  • Creating formatted strings? → Use strftime() with format codes (Method 2)
  • Building file paths? → Combine with pathlib.Path (Method 3)
  • Filtering data? → Compare .year and .month directly (Method 4)

For most production applications, combining datetime.now() with strftime() formatting gives you the flexibility to handle any date display or file naming requirement.