Python - Dates & Time
Overview
Estimated time: 20–30 minutes
Use datetime
and zoneinfo
to work with timezone-aware timestamps and format/parse dates safely.
Learning Objectives
- Create naive and aware datetimes; convert timezones.
- Format and parse with
strftime
/strptime
. - Use
timedelta
for arithmetic.
Prerequisites
Creating and converting
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
now_utc = datetime.now(timezone.utc)
now_ny = now_utc.astimezone(ZoneInfo("America/New_York"))
print(now_utc.isoformat())
print(now_ny.isoformat())
Formatting and parsing
from datetime import datetime
s = "2025-09-05 12:34:00"
dt = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
print(dt.strftime("%b %d, %Y %I:%M %p"))
Arithmetic
from datetime import datetime, timedelta
start = datetime(2025, 1, 1)
end = datetime(2025, 2, 1)
print((end - start).days) # 31
print(start + timedelta(days=10))
Common Pitfalls
- Using naive datetimes in multi-timezone apps; prefer timezone-aware.
- Hardcoding timezone offsets; use
zoneinfo
for DST safety.
Checks for Understanding
- How do you make a datetime timezone-aware?
- Which module provides IANA timezones in Python 3.9+?
Show answers
- Attach
tzinfo
(e.g.,timezone.utc
orZoneInfo(...)
). zoneinfo
Exercises
- Parse a timestamp string and convert it to UTC.
- Compute the duration between two user-supplied dates in days.