23. Dates, Times, and Time Zones

Working with dates and times is a common task in real programs. Python’s datetime module handles dates and times, and zoneinfo adds standard-library time zone support.

23.1. Creating dates and times

You can create date and datetime objects directly.

1from datetime import date, datetime
2
3
4birthday = date(2025, 7, 4)
5meeting = datetime(2025, 7, 4, 14, 30)
6
7print(birthday)
8print(meeting)

23.2. Current time

Use datetime.now() to get the current local date and time.

1from datetime import datetime
2
3
4now = datetime.now()
5print(now)

23.3. Formatting and parsing

strftime() formats a date or time as text, and strptime() parses text into a datetime.

1from datetime import datetime
2
3
4dt = datetime(2025, 12, 31, 23, 45)
5print(dt.strftime('%Y-%m-%d %H:%M'))
6
7parsed = datetime.strptime('2025-12-31 23:45', '%Y-%m-%d %H:%M')
8print(parsed)

23.4. Time zones with zoneinfo

Use zoneinfo.ZoneInfo when you need an aware datetime tied to a real time zone.

1from datetime import datetime
2from zoneinfo import ZoneInfo
3
4
5ny_time = datetime(2025, 1, 15, 9, 0, tzinfo=ZoneInfo('America/New_York'))
6london_time = ny_time.astimezone(ZoneInfo('Europe/London'))
7
8print(ny_time)
9print(london_time)

23.5. Why this matters

Dates and times often become tricky because formatting, parsing, and time zones all matter at once. It is worth learning the standard-library tools early so you do not end up treating times as plain strings everywhere in your code.

23.6. Exercise

Create a flight itinerary display. Start with a departure time in New York, convert it to London time, and print both values in a readable format. Then compute the arrival time after adding a flight duration of 7 hours and 15 minutes.