Sub topic 3
Adding, subtracting, and comparing dates
Assume you know basic Python syntax, lists, strings, and how to run a script. This chapter focuses on the datetime module, then combines it with random and math.
Date arithmetic
A date represents a calendar date. A datetime represents a date and a clock time. A timedelta represents a duration.
from datetime import date, datetime, timedelta
today = date(2026, 11, 26)
deadline = today + timedelta(days=14)
remaining = deadline - today
print(deadline) # 2026-12-10
print(remaining.days) # 14
print(deadline > today) # True
meeting = datetime(2026, 11, 26, 14, 30)
later = meeting + timedelta(hours=2)
print(later) # 2026-11-26 16:30:00You can compare dates and datetimes of the same general type. Do not compare a date directly with a datetime; convert one first when needed.
Formatting and parsing
Use isoformat() for a standard machine-readable string. Use strftime() to format output for people. Use strptime() or fromisoformat() to parse text.
from datetime import datetime
text = "2026-11-26 14:30"
meeting = datetime.strptime(text, "%Y-%m-%d %H:%M")
print(meeting.strftime("%d %B %Y at %H:%M"))
print(meeting.isoformat())
print(datetime.fromisoformat("2026-11-26T14:30:00"))Common format codes include %Y for a four-digit year, %m for a month, %d for a day, %H for a 24-hour hour, and %M for minutes.
Naive and aware datetimes
A naive datetime has no time-zone information. An aware datetime includes a time zone. Keep these kinds separate.
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
utc_time = datetime(2026, 11, 26, 12, 0, tzinfo=timezone.utc)
tokyo_time = utc_time.astimezone(ZoneInfo("Asia/Tokyo"))
print(tokyo_time) # 2026-11-26 21:00:00+09:00astimezone() changes the displayed zone while preserving the same instant. Mixing naive and aware datetimes in arithmetic raises TypeError.
Putting the modules together
Use random.Random for a reproducible choice, datetime for the resulting date, and math for calculations.
import math
import random
from datetime import date, timedelta
rng = random.Random(2026)
start = date(2026, 1, 1)
day = start + timedelta(days=rng.randrange(365))
distance = math.hypot(3, 4)
print(day.isoformat())
print(distance) # 5.0Exercise
How do you convert an aware UTC datetime to a local time zone?
Show answer
Call aware_datetime.astimezone(ZoneInfo("Region/City")).