Dates, timedeltas, formatting and parsing
Every date here is fixed, so the output is the same on every run. Change the format codes and predict the text first.
Python's datetime module has types for a date, a time of day, both together, and a length of time. Keep every moment as a time-zone-aware value, store and compare in UTC, show local time only at the edge, and write dates as ISO 8601 text.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 7 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write code that prints how many days are left between 10 October 2026 and 25 December 2026, in the form Days left: 76. Hint: subtract two date objects and read .days.
Parse the text "03 Mar 2026 18:45" with strptime and print the result in ISO 8601 (it should print 2026-03-03T18:45:00). Hint: %b is the short month name.
A meeting is at 15:00 in Asia/Kolkata on 1 July 2026. Print its time in UTC (HH:MM) and in America/New_York (HH:MM followed by the zone abbreviation, from %Z). Hint: make the meeting aware first, then use astimezone.
Write last_day(year, month) that returns the last date of a month. Find the first day of the next month and subtract one day. Print last_day(2028, 2) and last_day(2026, 12) on one line. Hint: December needs the year to go up by one and the month to wrap to 1.
Explain it without notes
What is the difference between a naive and an aware datetime, and why does Python refuse to compare them?
Why should a program store times in UTC, and when should it convert to a local zone?
What is the difference between astimezone and replace(tzinfo=...)?
Describe a daylight-saving bug and how to avoid it.
Why use time.monotonic() or perf_counter() to measure a duration instead of two datetime.now() calls?
Expected output
date: 2026-03-08
time: 14:30:05
datetime: 2026-03-08 14:30:05
parts: 2026 3 8 14 30
weekday (Mon=0): 6 Sunday
later: 2026-03-10 17:30:05
difference: 76 days, 0:00:00
days only: 76
total seconds: 183600.0
08 March 2026, 02:30 PM
2026-03-08
parsed: 2026-12-25 09:15:00 datetime
2026-03-08T14:30:05
2026-03-08 14:30:05
True
ValueError: time data '2026-13-01' does not match format '%Y-%m-%d'