← Back to Home

Python zoneinfo Tested: 6 Silent DST Errors

Pythontime zonesdaylight saving

At 1 a.m. on November 1 I dumped the logs of a service scheduled against America/New_York and found two records with identical timestamps, yet the table said their gap was 0 seconds. Higher up, a window that should have taken 60 minutes took 120. Nothing crashed. Every unit test was green.

The bug was not in the logging library. It was in four comparison rules of datetime, all of them written down in PEP 495 and almost never in tutorials. I tested six of them on CPython 3.13.14, Windows 11, tzdata 2025.2 (IANA 2025b), and each one reproduces in about ten lines. On the way I also checked China's own daylight saving years, 1986 to 1991, where "Beijing time is UTC+8" stops being true.

First, separate three things: the zone key, the offset, the DST flag

A ZoneInfo object holds an IANA key such as America/New_York. It does not store an offset; it stores a table of when to switch to which offset. utcoffset() returns the UTC offset for one specific instant, and dst() returns the part of that offset attributed to daylight saving. Read those three as one thing and you conclude New York is "always minus five".

On Windows there is a precondition. On my machine zoneinfo.TZPATH prints as an empty tuple, meaning the OS ships no time zone database at all and everything depends on the tzdata package from PyPI. The official docs are explicit: "Some systems, including notably Windows systems, do not have an IANA database available, and so for projects targeting cross-platform compatibility that require time zone data, it is recommended to declare a dependency on tzdata. If neither system data nor tzdata are available, all calls to ZoneInfo will raise ZoneInfoNotFoundError."

I removed site-packages from the path to reproduce a machine without tzdata, and even the key UTC fails:

zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key UTC'

That exception subclasses KeyError, so any code wrapping the lookup in except KeyError swallows it and keeps going with a naive datetime. That is the first silent failure in the chain.

Error one: a local time that never existed gets moved

On March 8, 2026, New York jumps from 02:00 straight to 03:00. The wall time 02:30 does not exist that day. Constructing it raises nothing:

foldutcoffsetconverted to UTCconverted backround trip closes
0-05:0007:3003:30 EDTno
1-04:0006:3001:30 ESTno

Neither result is 02:30. fold=0 uses the offset from before the transition and lands on 03:30 after it; fold=1 uses the offset from after the transition and lands on 01:30 before it. That is exactly what the documentation promises for fold: before-transition offset for 0, after-transition offset for 1. It never promises the wall time exists.

Detecting the trap takes three lines and no third-party library:

def kind(w):
    d0, d1 = w.replace(fold=0), w.replace(fold=1)
    if d0.utcoffset() == d1.utcoffset():
        return "ok"
    back = d0.astimezone(UTC).astimezone(w.tzinfo)
    return "gap" if back.replace(tzinfo=None) != w.replace(tzinfo=None) else "ambiguous"

The test is whether the two fold values agree on the offset. If they differ, convert with fold=0 and see whether you get the same wall clock back; if you do not, it is a gap, and if you do, it is an ambiguous time. This also answers "how do I know the timestamp the user typed does not exist" without wrapping everything in try/except.

Error two: two instants an hour apart compare equal

At 2 a.m. on November 1, 2026, New York falls back from EDT to EST, so the 01:00 to 01:59 hour happens twice. Take 01:30; the two fold values give two different real instants:

foldutcoffsettimestampin UTC
0-04:00179351100005:30
1-05:00179351460006:30

They are 3,600 seconds apart. Put both into one expression and this is what you get:

The same pair is equal in the wall-clock world and unequal in the instant world, and Python hands you the first one by default. PEP 495 says it plainly: "Naive and intra-zone comparisons will ignore the value of fold and return the same results as they do now. (This is the only way to preserve backward compatibility. If you need an aware intra-zone comparison that uses the fold, convert both sides to UTC first.)" The sentence in brackets is the only fix: convert both sides to UTC before comparing.

This one fabricates data. In the service above, records inside the repeated hour were deduplicated by a set, the request count in the report dropped by 50%, and every assertion still passed, because no line of code ever compared two times explicitly.

Error three: change the tzinfo object and the same instant stops being equal

If the previous error can be patched with "convert to UTC", this one is harder: the same code, with a different tzinfo object, flips the answer.

I took one wall time, 2026-11-01 01:30, attached different tzinfo objects, and compared each pair:

ComparisonResult of ==
The same ZoneInfo object (cache hit, a is b)True
ZoneInfo versus ZoneInfo.no_cache for the same keyFalse
America/New_York versus America/TorontoFalse
Two timezone(timedelta(hours=-4)) instancesTrue
Two custom tzinfo instances (hardcoded -4)True
New York versus Toronto at 12:00 in June (unambiguous)True

In the New York versus Toronto case both datetimes have the same wall clock, both report -04:00, and both convert to 05:30 UTC. Same instant, and == is False. The reason is an exception in PEP 495: "Whenever one or both of the operands in inter-zone comparison is such that its utcoffset() depends on the value of its fold attribute, the result is False."

The PEP also gives the formal definition. With toutc(t, fold) converting t to a naive UTC value under a given fold, then for two operands whose tzinfo are not the same object, t == s means toutc(t,0) == toutc(t,1) == toutc(s,0) == toutc(s,1). Inside an ambiguous hour toutc(t,0) is 05:30 and toutc(t,1) is 06:30, four values cannot all agree, so the answer is False immediately. A fixed-offset timezone object ignores fold, all four values agree, and the answer is True.

The docs attach a Caution to no_cache as well: "Using this constructor may change the semantics of your datetimes in surprising ways, only use it if you know that you need to." That is not boilerplate. It changes equality itself.

So you get the most counter-intuitive line in this article: a != b is true, and hash(a) == hash(b) is also true. Python allows it, since the invariant only requires equal objects to share a hash, not the other way round. But it means a dict can hold two different keys with the same hash, and any dedupe, sharding or cache key built on hashing gets two answers for one input.

Error four: adding one day is not adding 24 hours

The same trap is quieter in arithmetic. Start from 2026-03-07 12:00 EST (-05:00):

OperationResultReal seconds elapsed
plus timedelta(days=1)03-08 12:00 EDT82,800
plus timedelta(hours=24)03-08 12:00 EDT82,800
convert to UTC, add a day, convert back03-08 13:00 EDT86,400

Adding a day and adding 24 hours are the same operation here, because timedelta arithmetic on an aware datetime is wall-clock arithmetic, not absolute time. The per-hour table makes it obvious: from 03-07 22:00, adding 4 wall-clock hours lands on 03-08 02:00 EST after only 14,400 real seconds; adding 6 lands on 03-08 04:00 EDT after 18,000; adding 6 absolute hours lands on 05:00 EDT after 21,600. Three numbers, two meanings.

The consequence is that "expires in 30 days" style rules drift by an hour on the two transition days, and an hour usually stays inside tolerance, so nobody ever finds out. For real durations, convert to UTC first, then add.

Error five: string sorting inverts the order

The most common habit in logs and CSV exports is to sort isoformat() strings directly. Inside the repeated hour this reverses the order outright:

RecordStringTimestamp
A2026-11-01T01:00:00-05:001793512800
B2026-11-01T01:30:00-04:001793511000

Sorted as strings, A comes first because 01:00 is less than 01:30. Sorted by timestamp, B comes first, because B is 30 minutes earlier than A. The comparison is decided once it reads the first five digits of the time and never looks at the offset.

Aggregating across zones is worse. Three log lines read Shanghai 09:00+08:00 (01:00 UTC), UTC 08:30 (08:30 UTC) and New York 03:00-05:00 (08:00 UTC). String order is New York, UTC, Shanghai; instant order is Shanghai, New York, UTC. Exactly reversed.

There is one rule: sort on timestamp(), or normalise everything to UTC first. isoformat() is for humans to read and machines to parse, not for use as a sort key.

Error six: two silent traps on the reading side

The first five errors happen when you compute and compare. Reading input has two more.

The first is %Z. Parsing "2026-11-01 01:30 EDT" with datetime.strptime raises ValueError outright, because %Z only accepts the abbreviations in the local time.tzname, and this machine reports Chinese standard time. It gets worse when the abbreviation does match:

datetime.strptime("2026-11-01 01:30 ", "%Y-%m-%d %H:%M %Z")
-> datetime.datetime(2026, 11, 1, 1, 30)   # tzinfo is None

Parsed, no error, no time zone. Everything downstream then treats it as local time. Use %z (lowercase) to capture the offset, or parse ISO 8601 with fromisoformat.

The second is fromtimestamp() without a tz argument, which interprets the number in local time. The same timestamp 1793511000 gives 13:30 with no zone (this machine is UTC+8), 05:30 with UTC, and 01:30-04:00 with New York. Three lines, eight hours apart, zero errors. That code runs fine in a container and shifts wholesale on a UTC host, and an eight-hour shift looks entirely normal in a log.

Worth pinning down what fromisoformat accepts since 3.11: a trailing Z, both +0800 and +08:00, and even an ISO week date such as 2026-W45-5, which resolves to 2026-11-06. It does not accept Z and an offset together.

China had daylight saving too, from 1986 to 1991

"China has no DST, so I can ignore this" is true in 2026 and false in 1991. Query Asia/Shanghai backwards:

Dateutcoffsetdsttzname
1985-07-01+08:000CST
1986-07-01+09:001 hourCDT
1988-05-01+09:001 hourCDT
1991-09-15+08:000CST
2026-11-01+08:000CST

A full scan confirms the DST years are exactly 1986 through 1991, six of them. Note that May 1 was still CST in 1986 but already CDT in 1988, so the start date moved between years and one date cannot stand in for all six.

Two kinds of data break on this. Historical timestamps from 1986 to 1991 are off by a full hour if you convert under a fixed +8 assumption, and archive records phrased as "July 1 that year, at such a time" cannot share one formula across those years. Data from 2026 is unaffected; the same kind() helper reports ok for Shanghai at 01:30 on 2026-11-01.

Half-hour DST, and negative DST

Two edge cases prove the offset is not common sense.

Australia's Lord Howe Island runs a 30-minute DST. On 2026-10-04 the clock jumps from 02:00 to 02:30 and the offset goes from +10:30 to +11:00, a shift of 30 minutes. So 02:15 is a gap: fold=0 round-trips to 02:45 and fold=1 round-trips to 01:45, while 02:30 is fine because the transition ends just before it. Any assumption that DST is "always one hour" collapses here.

Ireland is stranger. Europe/Dublin returns dst() of -3600 seconds in January and 0 in July, with tznames GMT and IST. The zone marks winter as negative DST and summer as standard time. Code that decides "is it DST" by testing whether dst() is zero gets Ireland wrong all year.

Scheduling: one run too few, one run too many

Put those pieces together and you get a scheduler problem. Walking all 365 days of 2026 with the same helper, for a daily 02:30 job and a daily 01:30 job:

This is not theoretical. Any scheduler that stores "daily at HH:MM" in local wall time, in a zone with DST, loses one run and duplicates one run per year. The portable answer is to keep next-run instants in UTC internally and convert only for display. If a rule really must be "02:30 local", either pin it to a fixed UTC offset or document both transition-day behaviours explicitly.

Troubleshooting: six real exceptions

All six below are verbatim from this round of testing, not paraphrased.

Exception one: TypeError: can't compare offset-naive and offset-aware datetimes

Cause: one side came from fromisoformat without a zone, the other from now(UTC). Fix: normalise to aware at the boundary and backfill a zone explicitly on read, chosen by business rule, never guessed with replace.

Exception two: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).

Cause: utcnow() returns a naive value that reads like an aware one. Fix: use datetime.now(datetime.UTC). The warning only appears when a warnings filter is enabled, so it is silent by default.

Exception three: ValueError: Invalid isoformat string: '2026-11-06T06:10:00.123456+08:00Z'

Cause: Z and +08:00 are mutually exclusive spellings. Fix: strip the Z before parsing, or normalise to +00:00.

Exception four: zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key America/New York'

Cause: a space in the key. The message echoes your typo back, which makes it look like the database lacks US zones. Fix: use the canonical IANA key with an underscore, and validate against available_timezones() at startup.

Exception five: ValueError: offset must be a timedelta strictly between -timedelta(hours=24) and timedelta(hours=24), not datetime.timedelta(days=1, seconds=3600).

Cause: timezone(timedelta(hours=25)) written by hand. Fix: fixed offsets describe the gap to UTC, and no zone is more than 24 hours away; use ZoneInfo instead.

Exception six: ValueError: time data '2026-11-01 01:30 EDT' does not match format '%Y-%m-%d %H:%M %Z'

Cause: %Z only matches the local time.tzname. Fix: use %z or fromisoformat. If the source only gives abbreviations, maintain your own abbreviation-to-offset table instead of trusting strptime.

Six assertions before you ship

I compressed the findings into six checks, all of them assertable:

1. Every datetime is either aware or naive, never mixed; test each value with d.tzinfo is None.

2. Convert to UTC before cross-zone comparison, sorting or deduplication; never rely on == or on sets.

3. For real elapsed time, convert to UTC and then add the timedelta; use wall-clock arithmetic only for calendar days, and say so in a comment.

4. Run the kind() check on any wall time that arrives from a user or an external system, and handle gap and ambiguous separately.

5. Keep schedulers in UTC and convert for display; document the transition-day behaviour of any "daily at HH:MM" rule.

6. Pick one serialisation format (ISO 8601 with an offset is the safe one) and always sort on timestamps.

One honest note to close: none of this is specific to Python. Java's ZonedDateTime, JavaScript's Date and Go's time each have their own versions, but the premise is identical, that local time is a lookup table rather than a coordinate. The habit that saves you is not memorising six rules, it is making "store UTC, compare in UTC, convert only for humans" the default.

About this site: no affiliate links in this article, and every number above comes from tests I ran on 2026-11-06 plus the verbatim text of PEP 495 and the zoneinfo documentation. I hit the same family of bug earlier in the Python JSON serialisation piece, where naive datetimes serialise without an offset. If you are writing scheduled work, the huey, APScheduler and Celery comparison covers the scheduling layer, and retries and idempotency covers what happens when a job runs twice.

👉 Join Xiaomi MiMo Platform: Leading AI model platform with cost-effective inference

👉 Join Aliyun AI: Top AI products with exclusive coupons for business innovation

📌 This article was AI-assisted generated and human-reviewed | TechPassive — An AI-driven content testing site focused on real tool reviews

🔗 Recommended Tools

These are carefully selected tools. Using our affiliate links supports us to keep producing quality content:

As an Amazon Associate, I earn from qualifying purchases at no extra cost to you.

☁️ DigitalOcean Cloud ⚡ Vultr VPS 🤖 QoderWork CN (Refer & Earn) ☁️ Aliyun AI Products 📚 WordPress Books 🧠 AI & LLM Books 🏗️ System Design Books 🐳 Docker & K8s Books 🐧 Linux Admin Books 🐍 Python Books 🗄️ Database Books 🚀 DevOps & SRE Books 🤖 Xiaomi MiMo Platform
← Back to Home