Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.11 — Dates, Times and Time Zones
Python · Example 4 of 5

Calendar facts that surprise people

A month is not 30 days, 12/10/2026 has two meanings, and replace() labels while astimezone() converts.

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.

01

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.

02

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.

03

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.

04

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

01

What is the difference between a naive and an aware datetime, and why does Python refuse to compare them?

02

Why should a program store times in UTC, and when should it convert to a local zone?

03

What is the difference between astimezone and replace(tzinfo=...)?

04

Describe a daylight-saving bug and how to avoid it.

05

Why use time.monotonic() or perf_counter() to measure a duration instead of two datetime.now() calls?

Calendar facts that surprise people
Sign in to run this example in your browser.

Expected output

2026-03-02
28 31
-7
2026-10-12 2026-12-10
2028-02-29 2027-03-01
ValueError: day is out of range for month
ZoneInfoNotFoundError 'No time zone found with key Mars/Olympus'
2026-07-01T09:00:00+05:30
2026-07-01T04:30:00+01:00