# Time 11, Exercise 3: time zones in code and two classic date bugs # (zoneinfo ships with Python 3.9+; on Windows you may first need: py -m pip install tzdata) from datetime import datetime, timedelta, timezone from zoneinfo import ZoneInfo # Part 1: one instant, three wall clocks. Store UTC, convert for display. moment = datetime(2027, 7, 1, 12, 0, tzinfo=timezone.utc) for name in ("UTC", "Europe/London", "America/New_York", "Asia/Tokyo"): shown = moment.astimezone(ZoneInfo(name)) print(name.ljust(17), shown.strftime("%Y-%m-%d %H:%M %Z (UTC%z)")) # Part 2: a local time that does not exist, and one that happens twice (London, 2027). # Clocks go forward at 01:00 UTC on 28 March and back at 01:00 UTC on 31 October. london = ZoneInfo("Europe/London") before = datetime(2027, 3, 28, 0, 59, tzinfo=timezone.utc) after = before + timedelta(minutes=2) print("28 March:", before.astimezone(london).strftime("%H:%M %Z"), "->", after.astimezone(london).strftime("%H:%M %Z"), "(there is no 01:30 that night)") first = datetime(2027, 10, 31, 0, 30, tzinfo=timezone.utc).astimezone(london) second = datetime(2027, 10, 31, 1, 30, tzinfo=timezone.utc).astimezone(london) print("31 October:", first.strftime("%H:%M %Z"), "and", second.strftime("%H:%M %Z"), "- the wall time 01:30 happens twice") # Part 3: two bugs you can calculate. # (a) A counter of hundredths of a second, held in a signed 32-bit number, overflows after: hundredths = 2 ** 31 days = hundredths / 100 / 86400 print("signed 32-bit hundredths overflow after", round(days, 2), "days") # (b) Two-digit years: 2000 is read as 1900 if only "00" is stored. year_text = "00" print("two-digit year", year_text, "read as 19" + year_text, "gives", 1900 + int(year_text), "instead of", 2000 + int(year_text)) # (c) Leap-year rule: a naive "every 4 years" test wrongly calls 1900 a leap year. def naive(y): return y % 4 == 0 def correct(y): return y % 4 == 0 and (y % 100 != 0 or y % 400 == 0) for y in (1900, 2000, 2024, 2100): print(y, "naive:", naive(y), "correct:", correct(y)) # Output when run: # UTC 2027-07-01 12:00 UTC (UTC+0000) # Europe/London 2027-07-01 13:00 BST (UTC+0100) # America/New_York 2027-07-01 08:00 EDT (UTC-0400) # Asia/Tokyo 2027-07-01 21:00 JST (UTC+0900) # 28 March: 00:59 GMT -> 02:01 BST (there is no 01:30 that night) # 31 October: 01:30 BST and 01:30 GMT - the wall time 01:30 happens twice # signed 32-bit hundredths overflow after 248.55 days # two-digit year 00 read as 1900 gives 1900 instead of 2000 # 1900 naive: True correct: False # 2000 naive: True correct: True # 2024 naive: True correct: True # 2100 naive: True correct: False # Reading the output: the same instant shows as four different wall-clock times, so store UTC # and convert only for display. The last Sunday of March 2027 is the 28th and of October the # 31st (those are the dates used in the code). Counters that overflow, short years and a # sloppy leap rule are the raw material of most classic date bugs.