IC Improve Code Recipes

Recipe 15.3 · Python

Time Zones That Survive Daylight Saving

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

Users in several time zones need to see times in their own zone, and reports need "orders placed on March 8" to mean March 8 where the business is, not in UTC. The code converts with hard-coded offsets, and twice a year something is off by an hour.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

The first method is wrong from March to November. The second depends on the Kind of the incoming DateTime: if it is Local, the conversion starts from the server's zone, and if the zone name came from a browser on Linux it might not be found at all.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Time-zone conversion with a fixed offset and an unknown input kind (p331_r15_3_fixed_offset_time_zone_before.py)
"""Time-zone conversion with a fixed offset and an unknown input kind

Source: ImproveCode, Chapter 15, Recipe 15.3 "Time Zones That Survive Daylight Saving"
Section: The way it's often written
Book page: 331-332  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
TimeZoneInfo becomes zoneinfo.ZoneInfo; a naive datetime passed to astimezone() is
assumed to be in the server's zone, mirroring the DateTimeKind ambiguity.
"""

from datetime import datetime, timedelta
from zoneinfo import ZoneInfo

# Not to copy: fixed offsets and the server's zone.


def to_eastern(utc: datetime) -> datetime:
    return utc + timedelta(hours=-5)  # wrong half the year


def to_user_time(value: datetime, zone: str) -> datetime:
    tz = ZoneInfo(zone)
    return value.astimezone(tz)  # value's tzinfo?

The improved recipe

Usage snippet:

Requirements: Python 3.12+. Standard library only, nothing to install.

Python DST-safe time-zone helpers: find zone, convert, resolve local times, day ranges (p332_r15_3_zone_time_dst_helpers.py)
"""DST-safe time-zone helpers: find zone, convert, resolve local times, day ranges

Source: ImproveCode, Chapter 15, Recipe 15.3 "Time Zones That Survive Daylight Saving"
Section: The improved recipe
Book page: 332-333  -- original C# listing
Converted from C# to Python.
TimeZoneInfo becomes zoneinfo.ZoneInfo (IANA ids); DateTimeOffset becomes an aware
datetime with a fixed-offset tzinfo. Gaps are detected by a UTC round-trip and
ambiguous times by comparing fold=0/fold=1 offsets (larger offset wins, as in C#).
"""

from datetime import date, datetime, time, timedelta, timezone
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError


def find(zone_id: str) -> ZoneInfo:
    if zone_id is None or not zone_id.strip():
        raise ValueError("zone_id must not be empty.")
    try:
        return ZoneInfo(zone_id)
    except (ZoneInfoNotFoundError, ValueError):
        raise ValueError(f"Unknown time zone '{zone_id}'.") from None


def to_zone(instant: datetime, zone: ZoneInfo) -> datetime:
    if instant.tzinfo is None:
        raise ValueError("instant must be timezone-aware.")
    return instant.astimezone(zone)


def _offset(local: datetime, zone: ZoneInfo, fold: int = 0) -> timedelta:
    return local.replace(tzinfo=zone, fold=fold).utcoffset() or timedelta(0)


def _is_invalid(local: datetime, zone: ZoneInfo) -> bool:
    aware = local.replace(tzinfo=zone)
    round_trip = aware.astimezone(timezone.utc).astimezone(zone)
    return round_trip.replace(tzinfo=None) != local


def _is_ambiguous(local: datetime, zone: ZoneInfo) -> bool:
    return _offset(local, zone, 0) != _offset(local, zone, 1)


def from_local(local_time: datetime, zone: ZoneInfo) -> datetime:
    local = local_time.replace(tzinfo=None, fold=0)

    if _is_invalid(local, zone):
        # Inside a spring-forward gap: move past it.
        before = _offset(local + timedelta(hours=-6), zone)
        after = _offset(local + timedelta(hours=6), zone)
        local = local + (after - before)

    offset = (
        max(_offset(local, zone, 0), _offset(local, zone, 1))
        if _is_ambiguous(local, zone)
        else _offset(local, zone)
    )

    return local.replace(tzinfo=timezone(offset))


def day_range(day: date, zone: ZoneInfo) -> tuple[datetime, datetime]:
    start = datetime.combine(day, time.min)
    end = datetime.combine(day + timedelta(days=1), time.min)
    return from_local(start, zone), from_local(end, zone)

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Show an order time in Eastern and query one local day by UTC range (p333_r15_3_zone_time_day_range_usage.py)
"""Show an order time in Eastern and query one local day by UTC range

Source: ImproveCode, Chapter 15, Recipe 15.3 "Time Zones That Survive Daylight Saving"
Section: The improved recipe
Book page: 333  -- original C# listing
Converted from C# to Python.
Usage fragment wrapped in a function; SQL parameters become pyodbc-style ? placeholders.
"""

from datetime import UTC, date
from typing import Any

from p332_r15_3_zone_time_dst_helpers import day_range, find, to_zone


def example(order: Any) -> None:
    eastern = find("America/New_York")

    shown = to_zone(order.created_utc, eastern)

    start, end = day_range(date(2026, 3, 8), eastern)
    # WHERE CreatedUtc >= ? AND CreatedUtc < ?
    # pass start.astimezone(UTC) and end.astimezone(UTC) as parameters
    params = (start.astimezone(UTC), end.astimezone(UTC))
    _ = (shown, params)

How it works

Find wraps TimeZoneInfo.FindSystemTimeZoneById through its non-throwing sibling, TryFindSystemTimeZoneById (added in .NET 8), and gives a clear error with the bad ID in it.

There are two families of time zone IDs. Windows uses names like Eastern Standard Time; Linux, macOS, browsers and most APIs use IANA names like America/New_York. Before .NET 6 you could only look up the native kind for the operating system. Since .NET 6, FindSystemTimeZoneById accepts either kind on any platform, converting between them with ICU data. TimeZoneInfo.TryConvertIanaIdToWindowsId and TryConvertWindowsIdToIanaId are there when you need to translate explicitly. I store IANA IDs in user profiles, because that is what a browser reports and what every other system understands.

ToZone converts an instant. Because the input is a DateTimeOffset, there is no Kind to misread; the result carries the zone's offset at that moment, daylight saving included.

FromLocal handles the hard direction: a local wall-clock time typed by a user, turned into an instant. Two local times are special. In the spring, the hour from 2:00 to 3:00 doesn't exist in US Eastern time; IsInvalidTime catches it and the code moves the time forward by the size of the gap, the same thing a wall clock does. In the autumn, 1:30 happens twice; IsAmbiguousTime catches it and the code chooses the larger offset, which is the first occurrence. TimeZoneInfo.ConvertTimeToUtc would throw on the first case and silently pick standard time on the second.

DayRange returns a half-open range, start inclusive and end exclusive, for querying UTC columns. A day is not always 24 hours: March 8, 2026 in New York is 23 hours long, and the range reflects that.

Variations and pitfalls

  • IANA lookups on Windows rely on the ICU library that ships with Windows 10 version 1903 and later. If an app runs in globalization-invariant mode, test your zone lookups; conversion between ID families may not be available.
  • Never store an offset as if it were a zone. -05:00 tells you nothing about what the offset will be next July. Store the zone ID and the UTC instant.
  • For scheduling future local events ("9 a.m. every Monday in Chicago"), store the local time and the zone ID, and compute the instant each time. Time zone rules change by law, and a precomputed UTC value will drift.
  • If you need richer time zone handling, such as historical rules or calendars beyond the BCL, look at NodaTime. For most business apps, TimeZoneInfo with the rules above is enough.