Python
Datetime
Current Year
Current Month
Programming
Datetime current year and month in Python
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Python's datetime module provides datetime.now() to get the current date and time, with .year and .month attributes to extract the year and month as integers. For the current date only (without time), use date.today(). These values are commonly used for file naming, log timestamps, report headers, filtering data, and generating date ranges.
Getting Current Year and Month
Formatting Year and Month
Common Use Cases
File Naming
Filtering Data by Current Month
First and Last Day of Current Month
Generating Month Ranges
With Timezone Awareness
Using pandas
Common Pitfalls
- Using datetime.now() without timezone in production:
datetime.now()returns the system's local time, which varies between servers. In production, always usedatetime.now(timezone.utc)for consistent timestamps. The year/month can differ near midnight UTC depending on the server's timezone. - Assuming months are zero-indexed: Unlike JavaScript (where January is 0), Python months are 1-indexed (January is 1, December is 12). There is no need to add 1 to
.monthfor display. - Hardcoding days per month: Not all months have 31 days, and February varies by year. Use
calendar.monthrange(year, month)to get the correct number of days. Manually settingday=31for months with 30 days raisesValueError. - String formatting without zero-padding:
str(now.month)gives"3"for March, not"03". Usef"{now.month:02d}"ornow.strftime("%m")for zero-padded month numbers in filenames and date strings. - Confusing date.today() with datetime.now():
date.today()returns adateobject (no time).datetime.now()returns adatetimeobject (has time). Both have.yearand.month, butdateobjects cannot be used wheredatetimeis expected without conversion.
Summary
- Use
datetime.now().yearanddatetime.now().monthfor the current year and month as integers - Use
date.today()for a lighter alternative when you do not need the time component - Format with
strftime("%Y-%m")for strings orf"{month:02d}"for zero-padded numbers - Use
calendar.monthrange(year, month)to get the last day of a month - Always use timezone-aware datetimes (
datetime.now(timezone.utc)) in production - Python months are 1-indexed (January=1, December=12)
Related reading
- datetime dtypes in pandas read_csv
- datetime to string with time zone
- Dealing with multiple Python versions and PIP
- Debugging celery WorkerLostError with exitcode zero (Django 1.5.5 + celery 3.1.8 + RabbitMQ 3.1.3 on Heroku)
- Debugging python tests in TensorFlow
- deceptively simple implementation of topological sorting in python
- deciding among subprocess, multiprocessing, and thread in Python?
- Decode HTML entities in Python string?
.png&w=3840&q=75)
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.