The datetime
module is handy when dealing with dates, times, and durations in Python. The four core classes are:
datetime.datetime
- specific moment in time (2025-07-30 17:43:20)datetime.timedelta
- duration expressing the difference between twodatetime
ordate
instances to microsecond resolution.dateime.date
- calendar date (2025-07-30) asssuming gregorian calendardateime.time
- time of day (17:43:20)
Common patterns to remember
- Timestamps for filenames:
datetime.now().strftime("%Y%m%d_%H%M%S")
- Age calculations:
(date.today() - birth_date).days // 365
- Checking if recent:
timestamp > datetime.now() - timedelta(hours=24)
- Duration between events:
end_time - start_time
- Adding business days:
start_date + timedelta(days=5)
- End of day:
datetime.combine(date.today(), time.max)
- ISO format for APIs:
datetime.now().isoformat()
- Parsing user input with try/except for multiple formats
A sample of the format codes for formating the datetime objects:
Code | Meaning | Example |
---|---|---|
%Y | 4-digit year | 2025 |
%y | 2-digit year | 25 |
%m | Month (01-12) | 07 |
%B | Full month name | July |
%b | Short month name | Jul |
%d | Day (01-31) | 30 |
%H | Hour 24-hour (00-23) | 14 |
%I | Hour 12-hour (01-12) | 02 |
%M | Minute (00-59) | 30 |
%S | Second (00-59) | 45 |
%p | AM/PM | PM |
Gotchas to be mindful of
- Doesn’t work well with timezones
- timedelta doesn’t handle months/years reliably