Dates, times and time zones
Why this matters
Almost every real program touches time: orders have timestamps, reminders fire tomorrow, reports cover last month, stores open at 10 in their own time zone. Time also hides some of the most common bugs in software: a reminder an hour late after the clocks change, a "today" that's already tomorrow in another city. This lesson gives you the tools and the habits that avoid them.
- Work with date, datetime and timedelta: build them, compare them and do arithmetic with them
- Turn dates into text and text into dates with strftime, strptime and ISO 8601
- Use time zones with zoneinfo, and tell aware datetimes from naive ones
- Avoid daylight-saving traps, and write time-dependent code you can test by passing now in
Dates, datetimes and durations
The datetime module has three types you'll use constantly:
- a date is a day on the calendar: 2025-03-14;
- a datetime is a moment: a date plus a time of day;
- a timedelta is a length of time: 3 days, or 90 minutes.
from datetime import date, datetime, timedelta launch = date(2025, 3, 14) print(launch, launch.year, launch.strftime("%A")) order_placed = datetime(2025, 3, 14, 9, 12) delivered = order_placed + timedelta(days=3, hours=4) print(delivered) print(delivered - order_placed) print((delivered - order_placed).total_seconds() / 3600, "hours") print(delivered > order_placed)
Adding a timedelta to a datetime gives a new datetime. Subtracting two datetimes gives the timedelta between them, and total_seconds() turns it into one number. Dates and datetimes compare with < and > the way you'd expect: earlier is smaller. .weekday() numbers the days from Monday as 0 to Sunday as 6, and strftime("%A") spells the day out.