# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference) # Canonical Residual: https://corpusfetch.com/c/across-what-strict-utc-storage-and-iana-zoneinfo-gates-must-an-instance-process-timestamps-to-prevent-dst-ambiguity-and-time-shift-corruption.md # Remnant Warrant: https://corpusfetch.com/c/across-what-strict-utc-storage-and-iana-zoneinfo-gates-must-an-instance-process-timestamps-to-prevent-dst-ambiguity-and-time-shift-corruption.warrant.json # Markdown SHA-256: 9174f0e49a36eeb8acc2941d4fbce162592635888b04e501bad00e5e3e390ce4 # Code AST SHA-256: 408cd2a6a4cfb67186cabcf133a606e385a105e64289e1bdc096ccf19a1dd4fc # Verified Classes: InvalidTimestampError, StrictTimestampNormalizer # Defensive Guards: 5 fail-closed invariants (zero external deps) from datetime import datetime, timezone, timedelta from zoneinfo import ZoneInfo, ZoneInfoNotFoundError from typing import Any class InvalidTimestampError(ValueError): '''Raised when a timestamp string cannot be parsed or violates IANA validity.''' pass class StrictTimestampNormalizer: ''' Enforces time-zone correctness across system boundaries: 1. Parses inbound ISO strings or IANA wall-clock datetimes into strict UTC. 2. Handles DST ambiguous autumn folds (`fold=0` / `fold=1`) and spring gaps. 3. Normalizes all internal arithmetic and storage to UTC. 4. Renders back to target IANA wall-clock time strictly at egress. ''' @staticmethod def parse_to_utc( timestamp_input: str | datetime, *, user_iana_zone: str = "UTC", default_fold: int = 0, ) -> datetime: ''' Gate 1: Converts any input string or datetime into a normalized, timezone-aware UTC datetime. ''' try: zone = ZoneInfo(user_iana_zone) except ZoneInfoNotFoundError as exc: raise InvalidTimestampError(f"Invalid IANA time zone: {user_iana_zone!r}") from exc if isinstance(timestamp_input, datetime): dt = timestamp_input elif isinstance(timestamp_input, str): clean_str = timestamp_input.strip() try: # Handle trailing 'Z' shorthand for UTC if clean_str.endswith("Z"): clean_str = clean_str[:-1] + "+00:00" dt = datetime.fromisoformat(clean_str) except ValueError as exc: raise InvalidTimestampError(f"Malformed ISO-8601 timestamp: {timestamp_input!r}") from exc else: raise TypeError("Timestamp input must be a ISO-8601 string or datetime object") if dt.tzinfo is None: # Naive input: attach user's IANA zone with explicit fold handling try: localized = dt.replace(tzinfo=zone, fold=default_fold) except Exception as exc: raise InvalidTimestampError(f"Failed to localize naive time {dt} in {user_iana_zone}: {exc}") from exc return localized.astimezone(timezone.utc) else: # Already aware: convert directly to UTC return dt.astimezone(timezone.utc) @staticmethod def render_wall_clock( utc_dt: datetime, target_iana_zone: str, ) -> str: ''' Gate 4: Converts a strict UTC datetime into an ISO-8601 wall-clock string localized to the target IANA time zone for egress presentation. ''' if utc_dt.tzinfo is None: utc_dt = utc_dt.replace(tzinfo=timezone.utc) else: utc_dt = utc_dt.astimezone(timezone.utc) try: zone = ZoneInfo(target_iana_zone) except ZoneInfoNotFoundError as exc: raise InvalidTimestampError(f"Invalid target IANA zone: {target_iana_zone!r}") from exc local_dt = utc_dt.astimezone(zone) return local_dt.isoformat()