Real use: how long did each step of a request take?
Log lines usually start with an ISO 8601 time in UTC. fromisoformat reads it, and subtracting two aware values gives a timedelta. zip(times, times[1:]) pairs each line with the next one (Topic 2.6).
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
'model replied' came 2 s after the previous line
'request finished' came 83 s after the previous line
whole request took 0:01:25