๐ datetime, timedelta, strftime, timezone, UTCLESSON~15 min
Python datetime Module
Python's datetime module provides everything you need to work with dates and times: creation, formatting, parsing, arithmetic, and timezone handling.
Core Types
The module has four main types:
Type
Description
datetime.datetime
Combined date and time
datetime.date
Date only (year, month, day)
datetime.time
Time only (hour, minute, second, microsecond)
datetime.timedelta
Duration between two points in time
Getting the Current Time
Naive vs Aware: A naive datetime has no timezone; an aware datetime carries a tzinfo object. Always prefer aware datetimes in production code to avoid subtle bugs when comparing or converting times.
timedelta โ Duration Arithmetic
timedelta represents a duration and supports arithmetic with datetime objects:
strftime โ Formatting Dates
strftime converts a datetime to a formatted string using format codes:
Code
Meaning
Example
%Y
4-digit year
2024
%m
Month 01-12
03
%d
Day 01-31
15
%H
Hour 00-23
14
%M
Minute 00-59
30
%S
Second 00-59
45
%A
Full weekday
Friday
%B
Full month name
March
%I
Hour 01-12
02
%p
AM/PM
PM
%Z
Timezone name
UTC
strptime โ Parsing Strings to datetime
strptime (string parse time) is the inverse of strftime:
If the format string doesn't match the input, you get a ValueError โ always wrap in try/except when parsing user input.
ISO 8601 โ fromisoformat and isoformat
Python 3.7+ supports ISO 8601 format directly:
ISO 8601 is the recommended format for storing or transmitting datetimes โ it's unambiguous and universally supported.
Timezone-Aware Datetimes with zoneinfo
Python 3.9 introduced the zoneinfo module (replaces the third-party pytz):
Comparing and Sorting Datetimes
Practical Example: Age Calculator
Knowledge Check
What is the difference between a 'naive' and an 'aware' datetime in Python?
Which strftime format code produces the full month name (e.g. 'March')?
What does timedelta(days=1, hours=12).total_seconds() return?