The Datetime Module in Python Date and time manipulation is central to backend systems, financial transaction logs, scheduling engines, and data analytics. Python's built-in datetime module provides classes for managing calendar dates, times, durations, and timezones.
The module is structured into four primary classes:
date : Represents an idealized calendar date (Year, Month, Day).time : Represents an idealized time of day (Hour, Minute, Second, Microsecond), independent of any date.datetime : Combines both date and time into a single timestamp.timedelta : Represents a duration expressing the difference between two dates or times.1 from datetime import date , time , datetime , timedelta , timezone
2
3 # 1. Date instance
4 today = date . today ( )
5 print ( f"Today: { today . year } - { today . month : 02d } - { today . day : 02d } " )
6
7 # 2. Time instance
8 lunch_time = time ( 13 , 30 , 0 ) # 01:30:00 PM
9 print ( f"Lunch: { lunch_time } " )
10
11 # 3. Datetime instance
12 now = datetime . now ( )
13 print ( f"Current local timestamp: { now } " )
14
15 # 4. Timezone-Aware UTC Timestamp (Python 3.11+ recommended)
16 utc_now = datetime . now ( timezone . utc )
17 print ( f"Current UTC timestamp: { utc_now } " )
The strftime() method (String Format Time ) converts a datetime object into a custom formatted string according to format directives:
Directive Meaning Example Output %Y4-digit Year 2026%m2-digit Month (01-12) 09%d2-digit Day of Month (01-31) 12%HHour in 24-hour clock (00-23) 16%IHour in 12-hour clock (01-12) 04%MMinute (00-59) 15%SSecond (00-59) 30%pAM / PM PM%BFull Month Name September%AFull Weekday Name Saturday
1 from datetime import datetime
2
3 current = datetime . now ( )
4
5 # Standard formats:
6 print ( current . strftime ( "%d-%m-%Y %H:%M:%S" ) ) # 12-09-2026 16:15:30
7 print ( current . strftime ( "%A, %B %d, %Y" ) ) # Saturday, September 12, 2026
8 print ( current . strftime ( "%I:%M %p" ) ) # 04:15 PM
9 print ( current . isoformat ( ) ) # 2026-09-12T16:15:30.123456
The strptime() method (String Parse Time ) converts text strings from files, databases, or APIs into datetime objects using the corresponding format string:
1 from datetime import datetime
2
3 date_str = "2026-09-12 18:45"
4 parsed_dt = datetime . strptime ( date_str , "%Y-%m-%d %H:%M" )
5
6 print ( parsed_dt ) # 2026-09-12 18:45:00
7 print ( type ( parsed_dt ) ) # <class 'datetime.datetime'>
8 print ( "Year:" , parsed_dt . year )
Memory Trick:
- strftime -> F ormat to string.
- strptime -> P arse from string.
timedelta allows calculating deadlines, age, past dates, and future intervals effortlessly:
1 from datetime import datetime , timedelta
2
3 now = datetime . now ( )
4
5 # Calculate future deadline (14 days and 4 hours ahead)
6 trial_duration = timedelta ( days = 14 , hours = 4 )
7 expiry_date = now + trial_duration
8 print ( f"Subscription expires on: { expiry_date . strftime ( '%Y-%m-%d %H:%M' ) } " )
9
10 # Calculating difference between two dates
11 epoch_event = datetime ( 2026 , 1 , 1 )
12 elapsed = now - epoch_event
13 print ( f"Days elapsed since New Year 2026: { elapsed . days } days" )
14 print ( f"Total seconds elapsed: { elapsed . total_seconds ( ) : ,.0f } s" )
Naive : Contains no timezone information. Python cannot determine what geographical timezone it belongs to.Aware : Holds timezone metadata (such as UTC, IST, or EST) via the tzinfo parameter, preventing ambiguity across distributed servers.1 from datetime import datetime , timezone , timedelta
2
3 # Create timezone offset (IST: UTC + 5:30)
4 ist_zone = timezone ( timedelta ( hours = 5 , minutes = 30 ) , name = "IST" )
5
6 # Current time in IST
7 ist_time = datetime . now ( ist_zone )
8 print ( f"Time in India: { ist_time } " )
9 # Output: 2026-09-12 16:15:30.123456+05:30
1. Confusing Naive and Aware Datetimes A naive datetime object has no timezone (tzinfo=None). Comparing a naive datetime with a timezone-aware datetime raises a TypeError. In modern Python (3.11+), use datetime.now(timezone.utc).
2. Mixing up %m (Month) and %M (Minute) In strftime format strings:
%m: 2-digit month (01–12)%M: 2-digit minute (00–59)Scenario Write a function that calculates the exact number of days remaining until your next birthday using datetime.date and timedelta.
Complete Solution 1 from datetime import date
2
3 def days_until_birthday ( birth_month : int , birth_day : int ) - > int :
4 today = date . today ( )
5 this_year_bday = date ( today . year , birth_month , birth_day )
6
7 if this_year_bday < today :
8 next_bday = date ( today . year + 1 , birth_month , birth_day )
9 else :
10 next_bday = this_year_bday
11
12 return ( next_bday - today ) . days
13
14 # Example calculation
15 days = days_until_birthday ( 12 , 25 )
16 print ( f"Days until December 25th: { days } days" )
Expected Output 1 Days until December 25th: 85 days
Interactive Quiz • Knowledge Check
Practice Quiz Which method converts a datetime object into a custom formatted string?
A datetime.strptime()
B datetime.to_string()
C datetime.strftime()
D datetime.parse()
What does strptime("25/12/2026", "%d/%m/%Y") produce?
A A string "25-12-2026"
B A datetime object representing December 25, 2026
C A timestamp integer
D A syntax error
Which class represents the elapsed duration or difference between two datetime instances?
A datetime.duration
B datetime.timedelta
C datetime.timespan
D datetime.interval
What is the difference between a "naive" and an "aware" datetime object in Python?
A Naive objects have microsecond precision, while aware objects do not
B Aware objects contain explicit timezone offset information (tzinfo), whereas naive objects do not
C Naive objects are deprecated in Python 3
D Aware objects can only be created on Linux
What directive in strftime() represents the 4-digit year?
In the next lesson, we will continue your intermediate Python journey with Collections Module (10: Python Standard Libraries).
👉 Continue to Next Lesson: Collections Module →