Question presented to candidate: "Our service stores timestamps from users all over the world and shows them in each user's local time. How do you work with dates, times and time zones in Python, and what goes wrong around daylight saving time?"
What a strong answer should cover:
- The
datetimemodule types:date,time,datetime,timedelta,timezone; the difference between a naive datetime (notzinfo) and an aware one, and that comparing the two raisesTypeError - Store and compute in UTC (
datetime.now(timezone.utc)), convert to a local zone only for display withastimezone();datetime.utcnow()returns a naive value and is deprecated since Python 3.12 - Real time zones with
zoneinfo.ZoneInfo("Europe/London")(standard library since 3.9, PEP 615) backed by the IANA database (the OS copy or thetzdatapackage); a fixedtimezone(timedelta(hours=-5))offset is not a time zone because it never changes for DST - DST edge cases: the spring-forward gap (02:30 that never happens), the fall-back fold (01:30 twice, chosen with
fold=0/1), and that arithmetic within one zone is wall-clock arithmetic, so convert to UTC for elapsed time - Serialise with ISO 8601 (
isoformat()/fromisoformat(), which accepts a trailingZsince 3.11) or Unix timestamps;strptime/strftimefor custom formats;replace(tzinfo=...)attaches a zone whileastimezone()converts time.monotonic()/time.perf_counter()for measuring durations, not wall-clock datetimes
Clarifying questions expected:
- Do we need the user's real time zone (with DST rules) or only a fixed offset?
- What format do timestamps arrive in, and do they carry an offset?
- Do we care about calendar arithmetic (add one month, same local time tomorrow) or elapsed time?
Code / implementation expected: Optional โ store an aware UTC datetime, convert it to two ZoneInfo zones, and show one DST edge case.