### Install pytz from tarball Source: https://github.com/stub42/pytz/blob/master/src/README.rst Install pytz from a tarball using the standard Python distutils. Run as an administrative user. ```bash python setup.py install ``` -------------------------------- ### Install pytz with pip Source: https://github.com/stub42/pytz/blob/master/src/README.rst Install the latest version of pytz from PyPI using pip. ```bash pip install pytz ``` -------------------------------- ### Usage example for open_resource and resource_exists Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/pytz.md Example usage of pytz.open_resource and pytz.resource_exists. It opens the 'US/Eastern' zone file, reads the first 4 bytes (expected to be b'TZif'), and checks resource existence for both an existing and a non-existing resource. ```python import pytz fp = pytz.open_resource('US/Eastern') # binary file object over the zone file data = fp.read(4) # b'TZif' fp.close() assert pytz.resource_exists('US/Eastern') is True assert pytz.resource_exists('does/not/exist') is False ``` -------------------------------- ### Using LocalTimezone.utcoffset Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/reference.md Shows how to use the Local singleton from pytz.reference to get the platform's local offset. The example calls utcoffset(None) and prints the result, which is a timedelta representing the local offset (e.g., -1 day, 20:00:00 for EST). ```python from pytz.reference import Local aware = Local.utcoffset(None) print(aware) # platform local offset, e.g. -1 day, 20:00:00 (EST) ``` -------------------------------- ### Usage example for FixedOffset Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/reference.md Shows how to create FixedOffset instances and call their methods. Note that FixedOffset(0, "UTC") is distinct from pytz.utc. ```python from pytz.reference import FixedOffset moscow = FixedOffset(180, "Moscow") print(moscow.utcoffset(None)) # 3:00:00 print(moscow.tzname(None)) # Moscow utc_by_hand = FixedOffset(0, "UTC") print(utc_by_hand.tzname(None)) # UTC — a distinct object from pytz.utc ``` -------------------------------- ### pytz.utc / pytz.UTC Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/pytz.md Documentation for the UTC singleton instance in the pytz library, covering its methods and usage examples. ```APIDOC ## `pytz.utc` / `pytz.UTC` — UTC singleton ### Description Provides the UTC timezone as a singleton instance. It is an optimized UTC implementation that unpickles to the same module-level global instance. The exported names `utc` and `UTC` refer to the singleton instance, not the class. ### Import Path `pytz.utc`, `pytz.UTC`, or `pytz.timezone('UTC')` ### Methods #### `fromutc(dt)` - **Parameters**: `dt` (datetime) - Required - The datetime to convert. - **Returns**: If `dt` is naive, returns `self.localize(dt)`. Otherwise, returns the result of the superclass `fromutc`. #### `utcoffset(dt)` - **Parameters**: `dt` (datetime) - Required - The datetime. - **Returns**: Always `datetime.timedelta(0)`. #### `tzname(dt)` - **Parameters**: `dt` (datetime) - Required - The datetime. - **Returns**: Always `'UTC'`. #### `dst(dt)` - **Parameters**: `dt` (datetime) - Required - The datetime. - **Returns**: Always `datetime.timedelta(0)`. #### `localize(dt, is_dst=False)` - **Parameters**: - `dt` (datetime) - Required - The naive datetime to localize. - `is_dst` (bool) - Optional - Default `False`. - **Returns**: A datetime with `tzinfo` set to `self`. - **Raises**: `ValueError` if `dt.tzinfo` is already set. #### `normalize(dt, is_dst=False)` - **Parameters**: - `dt` (datetime) - Required - The datetime to normalize. - `is_dst` (bool) - Optional - Default `False`. - **Returns**: If `dt.tzinfo is self`, returns `dt` unchanged. If `dt.tzinfo` is `None`, raises `ValueError('Naive time - no tzinfo set')`. Otherwise, returns `dt.astimezone(self)`. #### `__reduce__()` - **Returns**: `(_UTC, ())` — pickle always resolves to the singleton via `_UTC()`. #### `__repr__()` / `__str__()` - **Returns**: `''` / `'UTC'` respectively. ### Examples ```python from datetime import datetime from pytz import utc, UTC, timezone assert utc is UTC is timezone('UTC') aware = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc) naive = datetime(2002, 10, 27, 6, 0, 0) local = utc.localize(naive) # 2002-10-27 06:00:00+00:00 back = utc.normalize(local) # same object, unchanged try: utc.localize(aware) # tzinfo already set except ValueError as e: print(e) # 'Not naive datetime (tzinfo is already set)' ``` ``` -------------------------------- ### FixedOffset usage example Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/pytz.md Demonstrates creating fixed-offset timezones, memoization (same instance for same offset), special-casing of zero offset to UTC, and the ValueError raised for offsets >= 1440. ```python from pytz import FixedOffset, UTC ist = FixedOffset(330) # UTC+5:30 — pytz.FixedOffset(330) same = FixedOffset(330) assert ist is same # one instance per offset utc_tz = FixedOffset(0) assert utc_tz is UTC # zero offset is special-cased try: FixedOffset(1440) except ValueError as e: print(e) # ('absolute offset is too large', 1440) ``` -------------------------------- ### Set up pytz dev container with apt and setuptools bootstrap Source: https://github.com/stub42/pytz/blob/master/deps.rst Commands to prepare a development container for pytz: generate locales, add the deadsnakes PPA, update apt, install build/test/packaging tools and multiple Python versions, then bootstrap setuptools for legacy Python 2.4-3.4 via wget piped to each interpreter. ```bash locale-gen add-apt-repository ppa:deadsnakes/ppa apt update apt install tox bzr build-essential twine python-all python-all-dev python3-all python3-all-dev python3-docutils python3-sphinx python3-flake8 python-flake8 python2.4-complete python2.5-complete python2.6-complete python3.1-complete python3.2-complete python3.3-complete python3.4-complete python3.5 python3.5-dev python3.7 python3.7-dev python-wheel python3-wheel python-pip python3-pip wget https://raw.githubusercontent.com/pypa/setuptools/bootstrap-py24/ez_setup.py -O - | python2.4 wget https://raw.githubusercontent.com/pypa/setuptools/bootstrap-py24/ez_setup.py -O - | python2.5 wget https://bootstrap.pypa.io/ez_setup.py -O - | python2.6 wget https://bootstrap.pypa.io/ez_setup.py -O - | python3.1 wget https://bootstrap.pypa.io/ez_setup.py -O - | python3.2 wget https://bootstrap.pypa.io/ez_setup.py -O - | python3.3 wget https://bootstrap.pypa.io/ez_setup.py -O - | python3.4 ``` -------------------------------- ### LazyDict usage example with country_timezones Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/lazy.md Example usage of LazyDict as used by pytz.country_timezones. First access fills from zone.tab. Demonstrates key upper-casing and KeyError on unknown codes. ```python from pytz import country_timezones codes = set(country_timezones.keys()) # first access fills from zone.tab print(len(codes)) # ~250 country codes print(country_timezones['nz']) # ['Pacific/Auckland', 'Pacific/Chatham'] print(country_timezones['NZ']) # same value (key upper-cased) try: country_timezones['XXX'] except KeyError: print('unknown code') ``` -------------------------------- ### FixedOffset(offset, _tzinfos={}) Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/pytz.md Documentation for the FixedOffset factory function, including parameters, return value, exceptions, and usage example. ```APIDOC ## `FixedOffset(offset, _tzinfos={})` ### Description Returns a fixed-offset timezone based on a number of minutes. A memoizing factory that returns a `_FixedOffset` instance, with `offset == 0` special-cased to return `UTC`. ### Signature ```python FixedOffset(offset, _tzinfos={}) ``` ### Parameters - **offset** (`int`) - Required - Offset from UTC in minutes. Must satisfy `abs(offset) < 1440`. `0` is special-cased to return `UTC`. - **_tzinfos** (`dict`) - Optional - Internal memoization store mapping minute-offset to instance (one instance per offset). Defaults to `{}`. ### Return Value - `pytz.utc` when `offset == 0`, otherwise a `pytz.FixedOffset` `_FixedOffset` instance. The same instance is returned for repeated calls with the same offset, and after unpickling. ### Exceptions - `ValueError` - Raised when `abs(minutes) >= 1440` with message `'absolute offset is too large'`. ### Example ```python from pytz import FixedOffset, UTC ist = FixedOffset(330) # UTC+5:30 — pytz.FixedOffset(330) same = FixedOffset(330) assert ist is same # one instance per offset utc_tz = FixedOffset(0) assert utc_tz is UTC # zero offset is special-cased try: FixedOffset(1440) except ValueError as e: print(e) # ('absolute offset is too large', 1440) ``` ``` -------------------------------- ### LazyList usage example Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/lazy.md Demonstrates creating a LazyList with an iterator and triggering the fill on len(), then accessing the list. The fill happens only once. ```python from pytz.lazy import LazyList lazy = LazyList(iter(['UTC', 'GMT'])) print(len(lazy)) # triggers fill: 2 print(lazy) # ['UTC', 'GMT'] — fill already done, no re-population ``` -------------------------------- ### pytz DstTzInfo localize, normalize, and tzname examples Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/tzinfo.md Demonstrates localize, normalize, and tzname behavior on ambiguous and non-existent times. Shows that localize with is_dst=True/False resolves ambiguous wall-clock times, normalize corrects arithmetic crossing a DST boundary, and strict mode (is_dst=None) raises NonExistentTimeError or AmbiguousTimeError. Also shows tzname raising AmbiguousTimeError when is_dst is omitted on an ambiguous instant. ```python from datetime import datetime, timedelta from pytz import timezone eastern = timezone('US/Eastern') # localize: ambiguous end-of-DST wallclock time dt = datetime(2002, 10, 27, 1, 30, 0) edt = eastern.localize(dt, is_dst=True) # 2002-10-27 01:30:00 EDT-0400 est = eastern.localize(dt, is_dst=False) # 2002-10-27 01:30:00 EST-0500 # normalize: fix arithmetic that crossed a DST boundary before = eastern.localize(datetime(2002, 10, 27, 1, 0, 0)) - timedelta(minutes=10) fixed = eastern.normalize(before) # 2002-10-27 01:50:00 EDT-0400 # non-existent time, strict mode from pytz.exceptions import NonExistentTimeError, AmbiguousTimeError try: eastern.localize(datetime(2002, 4, 7, 2, 30, 0), is_dst=None) except NonExistentTimeError: print('never happened') try: eastern.localize(datetime(2002, 10, 27, 1, 30, 0), is_dst=None) except AmbiguousTimeError: print('happened twice') # tzname on an ambiguous instant without is_dst raises too tz = timezone('America/St_Johns') ambiguous = datetime(2009, 10, 31, 23, 30) try: tz.tzname(ambiguous) except AmbiguousTimeError: print('need is_dst') print(tz.tzname(ambiguous, is_dst=True)) # 'NDT' print(tz.tzname(ambiguous, is_dst=False)) # 'NST' ``` -------------------------------- ### Catch any pytz error with Error Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/exceptions.md Shows how to catch all pytz exceptions using the Error base class. The example catches UnknownTimeZoneError, AmbiguousTimeError, and NonExistentTimeError. ```python from pytz.exceptions import Error try: timezone('Not/AZone') except Error: pass # catches UnknownTimeZoneError, AmbiguousTimeError, NonExistentTimeError ``` -------------------------------- ### UTC usage example Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/pytz.md Demonstrates identity checks, localize, normalize, and error handling. localize raises ValueError if tzinfo is already set. normalize returns the same object when tzinfo is self. ```python from datetime import datetime from pytz import utc, UTC, timezone assert utc is UTC is timezone('UTC') aware = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc) naive = datetime(2002, 10, 27, 6, 0, 0) local = utc.localize(naive) # 2002-10-27 06:00:00+00:00 back = utc.normalize(local) # same object, unchanged try: utc.localize(aware) # tzinfo already set except ValueError as e: print(e) # 'Not naive datetime (tzinfo is already set)' ``` -------------------------------- ### USTimeZone class Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/reference.md Documentation for the USTimeZone class, its constructor, methods, and usage example. ```APIDOC ## `USTimeZone` class ### Description A complete implementation of the (pre-2007) US DST rules: DST from 2am on the first Sunday in April until 2am DST on the last Sunday in October. This class extends `tzinfo` and is used to create time zones with standard and daylight saving time offsets. ### Constructor | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `hours` | `int` | yes | — | Standard-time offset from UTC in hours (negative for west) | | `reprname` | `str` | yes | — | Name returned by `__repr__` | | `stdname` | `str` | yes | — | Abbreviation returned by `tzname()` during standard time | | `dstname` | `str` | yes | — | Abbreviation returned by `tzname()` during daylight saving time | ### Methods | Method | Signature | Returns | |--------|-----------|---------| | `__repr__` | `__repr__(self)` | `self.reprname` | | `tzname` | `tzname(self, dt)` | `self.dstname` if `self.dst(dt)` else `self.stdname` | | `utcoffset` | `utcoffset(self, dt)` | `self.stdoffset + self.dst(dt)` | | `dst` | `dst(self, dt)` | `ZERO` when `dt is None` or `dt.tzinfo is None`; `assert dt.tzinfo is self`; `HOUR` (1 hour) when `start <= dt.replace(tzinfo=None) < end`, else `ZERO` | ### Example ```python from datetime import datetime from pytz.reference import Eastern, UTC dt = datetime(2002, 10, 27, 0, 30, tzinfo=Eastern) print(dt.utcoffset()) # -1 day, 20:00:00 (EDT) print(dt.astimezone(UTC)) # 2002-10-27 04:30:00+00:00 # NOTE: reference zones do NOT perform pytz-style DST correction on # arithmetic — the famous "two hours apart" pitfall: one_hour_later = dt + timedelta(hours=1) print(one_hour_later.astimezone(UTC)) # 2002-10-27 06:30:00+00:00 (2 real hours) ``` ``` -------------------------------- ### StaticTzInfo usage example Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/tzinfo.md Shows how to use StaticTzInfo with the GMT timezone: localize a naive datetime, normalize it (no-op), and handle the ValueError when localizing an already-aware datetime. ```python from pytz import timezone from pytz.tzinfo import StaticTzInfo gmt = timezone('GMT') assert isinstance(gmt, StaticTzInfo) naive = datetime(2011, 5, 8, 1, 2, 3) loc = gmt.localize(naive) # 2011-05-08 01:02:03+00:00 assert gmt.normalize(loc) is loc # no-op for static zones try: gmt.localize(loc) # already aware except ValueError as e: print(e) # Not naive datetime (tzinfo is already set) ``` -------------------------------- ### UTC conversion shortcut with normalize Source: https://github.com/stub42/pytz/blob/master/src/README.rst Shows a shortcut for UTC conversions using normalize() when there are no DST transitions. The example converts a UTC datetime to Australia/Sydney and back, demonstrating that normalize() is not necessary for UTC. ```python >>> utc_dt = datetime.fromtimestamp(1143408899, tz=utc) >>> utc_dt.strftime(fmt) '2006-03-26 21:34:59 UTC+0000' >>> au_tz = timezone('Australia/Sydney') >>> au_dt = au_tz.normalize(utc_dt.astimezone(au_tz)) >>> au_dt.strftime(fmt) '2006-03-27 08:34:59 AEDT+1100' >>> utc_dt2 = au_dt.astimezone(utc) >>> utc_dt2.strftime(fmt) '2006-03-26 21:34:59 UTC+0000' ``` -------------------------------- ### Pickle round-trip with unpickler Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/tzinfo.md Example of pickling and unpickling a localized datetime, which transitively calls unpickler via pytz._p. It verifies that the unpickled datetime preserves the UTC offset and equality. ```python import pickle from datetime import datetime from pytz import timezone eastern = timezone('US/Eastern') dt = eastern.localize(datetime(2002, 10, 27, 1, 30)) new = pickle.loads(pickle.dumps(dt, 1)) # via pytz._p -> unpickler assert new.tzinfo._utcoffset == dt.tzinfo._utcoffset assert new == dt ``` -------------------------------- ### tzinfo API with is_dst parameter Source: https://github.com/stub42/pytz/blob/master/src/README.rst Demonstrates the extended tzinfo API with the is_dst parameter. The example uses the America/St_Johns timezone and shows how utcoffset(), dst(), and tzname() behave for normal and ambiguous timestamps with is_dst=True and is_dst=False. ```python >>> tz = timezone('America/St_Johns') >>> normal = datetime(2009, 9, 1) >>> ambiguous = datetime(2009, 10, 31, 23, 30) ``` ```python >>> print(tz.utcoffset(normal, is_dst=True)) -1 day, 21:30:00 >>> print(tz.dst(normal, is_dst=True)) 1:00:00 >>> tz.tzname(normal, is_dst=True) 'NDT' ``` ```python >>> print(tz.utcoffset(ambiguous, is_dst=True)) -1 day, 21:30:00 >>> print(tz.dst(ambiguous, is_dst=True)) 1:00:00 >>> tz.tzname(ambiguous, is_dst=True) 'NDT' ``` ```python >>> print(tz.utcoffset(normal, is_dst=False)) -1 day, 21:30:00 >>> tz.dst(normal, is_dst=False).seconds 3600 >>> tz.tzname(normal, is_dst=False) 'NDT' ``` ```python >>> print(tz.utcoffset(ambiguous, is_dst=False)) -1 day, 20:30:00 >>> tz.dst(ambiguous, is_dst=False) datetime.timedelta(0) >>> tz.tzname(ambiguous, is_dst=False) 'NST' ``` -------------------------------- ### Example usage of LazySet with timezone strings Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/lazy.md Shows how to use `LazySet` with a list of timezone names. The first membership test triggers the fill, and subsequent set operations delegate to the built-in `set` after the lazy wrappers are removed. ```python from pytz.lazy import LazySet zones = LazySet(['US/Eastern', 'UTC']) print('US/Eastern' in zones) # True — fill on first membership test print(len(zones & {'UTC'})) # 1 — set algebra delegated to builtin after fill ``` -------------------------------- ### Initialize timezones and format string Source: https://github.com/stub42/pytz/blob/master/src/README.rst Set up timezone objects for UTC, US/Eastern, and Europe/Amsterdam, and define a formatting string for localized times. ```python >>> from datetime import datetime, timedelta >>> from pytz import timezone >>> import pytz >>> utc = pytz.utc >>> utc.zone 'UTC' >>> eastern = timezone('US/Eastern') >>> eastern.zone 'US/Eastern' >>> amsterdam = timezone('Europe/Amsterdam') >>> fmt = '%Y-%m-%d %H:%M:%S %Z%z' ``` -------------------------------- ### Populate _tzinfos registry in DstTzInfo.__init__ Source: https://github.com/stub42/pytz/blob/master/_autodocs/types.md Populates the shared _tzinfos registry in DstTzInfo.__init__. The registry maps ttinfo records to per-state DstTzInfo instances, allowing fromutc to attach the exact state instance via self._tzinfos[inf]. ```python _tzinfos = {} self._tzinfos = _tzinfos self._utcoffset, self._dst, self._tzname = self._transition_info[0] _tzinfos[self._transition_info[0]] = self for inf in self._transition_info[1:]: if inf not in _tzinfos: _tzinfos[inf] = self.__class__(inf, _tzinfos) ``` -------------------------------- ### Configure pytz with PYTZ_TZDATADIR and PYTZ_SKIPEXISTSCHECK Source: https://github.com/stub42/pytz/blob/master/_autodocs/configuration.md Shows how to configure pytz at runtime using the PYTZ_TZDATADIR and PYTZ_SKIPEXISTSCHECK environment variables. The bash version exports the variables for the shell session; the Python version sets them via os.environ before calling pytz.timezone(). When PYTZ_TZDATADIR is set, open_resource() resolves paths under that directory and skips the in-package zoneinfo/ and fallback lookups. PYTZ_SKIPEXISTSCHECK makes resource_exists() return True immediately, skipping filesystem checks. ```bash # Resolve zones from a custom tzdata directory instead of the wheel's zoneinfo/ export PYTZ_TZDATADIR=/usr/share/zoneinfo # Skip existence checks at import time export PYTZ_SKIPEXISTSCHECK=1 ``` ```python import os, pytz os.environ['PYTZ_TZDATADIR'] = '/usr/share/zoneinfo' os.environ['PYTZ_SKIPEXISTSCHECK'] = '1' eastern = pytz.timezone('US/Eastern') # loaded from PYTZ_TZDATADIR ``` -------------------------------- ### Get country name with pytz.country_names Source: https://github.com/stub42/pytz/blob/master/src/README.rst Looks up the English country name from the ISO 3166 country code using the pytz.country_names dictionary. ```python >>> print(pytz.country_names['nz']) New Zealand ``` -------------------------------- ### build_tzinfo(zone, fp) - parse tzfile(5) and create tzinfo Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/tzfile.md Builds a datetime.tzinfo implementation for a zone from an open binary tzfile(5) stream. The function reads the header, validates the magic bytes, parses transition times and ttinfo structures, and returns an instance of a dynamically-created subclass of StaticTzInfo or DstTzInfo. It handles both static zones (no transitions) and zones with DST transitions, rounding offsets to the nearest minute. ```python def build_tzinfo(zone, fp): head_fmt = '>4s c 15x 6l' head_size = calcsize(head_fmt) (magic, format, ttisgmtcnt, ttisstdcnt, leapcnt, timecnt, typecnt, charcnt) = unpack(head_fmt, fp.read(head_size)) # Make sure it is a tzfile(5) file assert magic == _byte_string('TZif'), 'Got magic %s' % repr(magic) # Read out the transition times, localtime indices and ttinfo structures. data_fmt = '>%(timecnt)dl %(timecnt)dB %(ttinfo)s %(charcnt)ds' % dict( timecnt=timecnt, ttinfo='lBB' * typecnt, charcnt=charcnt) data_size = calcsize(data_fmt) data = unpack(data_fmt, fp.read(data_size)) # make sure we unpacked the right number of values assert len(data) == 2 * timecnt + 3 * typecnt + 1 transitions = [memorized_datetime(trans) for trans in data[:timecnt]] lindexes = list(data[timecnt:2 * timecnt]) ttinfo_raw = data[2 * timecnt:-1] tznames_raw = data[-1] del data # Process ttinfo into separate structs ttinfo = [] tznames = {} i = 0 while i < len(ttinfo_raw): # have we looked up this timezone name yet? tzname_offset = ttinfo_raw[i + 2] if tzname_offset not in tznames: nul = tznames_raw.find(_NULL, tzname_offset) if nul < 0: nul = len(tznames_raw) tznames[tzname_offset] = _std_string( tznames_raw[tzname_offset:nul]) ttinfo.append((ttinfo_raw[i], bool(ttinfo_raw[i + 1]), tznames[tzname_offset])) i += 3 # Now build the timezone object if len(ttinfo) == 1 or len(transitions) == 0: ttinfo[0][0], ttinfo[0][2] cls = type(zone, (StaticTzInfo,), dict( zone=zone, _utcoffset=memorized_timedelta(ttinfo[0][0]), _tzname=ttinfo[0][2])) else: # Early dates use the first standard time ttinfo i = 0 while ttinfo[i][1]: i += 1 if ttinfo[i] == ttinfo[lindexes[0]]: transitions[0] = datetime.min else: transitions.insert(0, datetime.min) lindexes.insert(0, i) # calculate transition info transition_info = [] for i in range(len(transitions)): inf = ttinfo[lindexes[i]] utcoffset = inf[0] if not inf[1]: dst = 0 else: for j in range(i - 1, -1, -1): prev_inf = ttinfo[lindexes[j]] if not prev_inf[1]: break dst = inf[0] - prev_inf[0] # dst offset # Bad dst? Look further. DST > 24 hours happens when # a timezone has moved across the international dateline. # DST <= 0 can be a zone realignment (e.g. Vilnius MSK->CEST); # or legitimate negative DST (e.g. Morocco, Ireland). if dst <= 0 or dst > 3600 * 3: for j in range(i + 1, len(transitions)): stdinf = ttinfo[lindexes[j]] if not stdinf[1]: dst = inf[0] - stdinf[0] if 0 < abs(dst) <= 3600 * 3: break # Found a useful std time. tzname = inf[2] # Round utcoffset and dst to the nearest minute or the # datetime library will complain. Conversions to these timezones # might be up to plus or minus 30 seconds out, but it is # the best we can do. utcoffset = int((utcoffset + 30) // 60) * 60 dst = int((dst + 30) // 60) * 60 transition_info.append(memorized_ttinfo(utcoffset, dst, tzname)) cls = type(zone, (DstTzInfo,), dict( zone=zone, _utc_transition_times=transitions, _transition_info=transition_info)) return cls() ``` -------------------------------- ### Helper functions and constants Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/reference.md Documentation for the helper function `first_sunday_on_or_after` and constants `DSTSTART`, `DSTEND`, and `UTC`. ```APIDOC ## Helper functions and constants ### Description Helper function and constants used to compute DST boundaries. These are exported from `pytz.reference` and can be used directly. ### Helpers | Name | Type | Description | |------|------|-------------| | `first_sunday_on_or_after(dt)` | function | Returns the first Sunday at-or-after `dt` (`days_to_go = 6 - dt.weekday()`), used to compute DST boundaries | | `DSTSTART` | `datetime.datetime` | `datetime(1, 4, 1, 2)` — DST begins 2am first Sunday in April | | `DSTEND` | `datetime.datetime` | `datetime(1, 10, 25, 1)` — DST ends 2am DST (1am standard) last Sunday in October | | `UTC` | `pytz.utc` singleton | re-export from the top-level package | ``` -------------------------------- ### StaticTzInfo.__reduce__ Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/tzinfo.md Provides pickling support that keys on the zone name to maintain singleton behavior and handle database changes. ```APIDOC ## StaticTzInfo.__reduce__ ### Description Provides pickling support that keys on the zone name to maintain singleton behavior and handle database changes. ### Method __reduce__ ### Signature __reduce__(self) ### Returns - **tuple** - A tuple (pytz._p, (self.zone,)) used for pickling. ### Example ```python import pickle from pytz import timezone gmt = timezone('GMT') data = pickle.dumps(gmt) ``` ``` -------------------------------- ### DstTzInfo methods: fromutc, normalize, localize, utcoffset, dst, tzname, __repr__, __reduce__ Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/tzinfo.md The DstTzInfo class implements the core timezone methods for pytz. fromutc converts a UTC datetime to local time using transition tables; normalize corrects a datetime's tzinfo to the proper offset; localize attaches tzinfo to a naive datetime; utcoffset, dst, and tzname return the offset, DST amount, and name, optionally localizing first; __repr__ formats a readable representation; __reduce__ supports pickling while preserving the zone singleton. ```python def fromutc(self, dt): '''See datetime.tzinfo.fromutc''' if (dt.tzinfo is not None and getattr(dt.tzinfo, '_tzinfos', None) is not self._tzinfos): raise ValueError('fromutc: dt.tzinfo is not self') dt = dt.replace(tzinfo=None) idx = max(0, bisect_right(self._utc_transition_times, dt) - 1) inf = self._transition_info[idx] return (dt + inf[0]).replace(tzinfo=self._tzinfos[inf]) ``` ```python def normalize(self, dt): '''Correct the timezone information on the given datetime ... ''' if dt.tzinfo is None: raise ValueError('Naive time - no tzinfo set') # Convert dt in localtime to UTC offset = dt.tzinfo._utcoffset dt = dt.replace(tzinfo=None) dt = dt - offset # convert it back, and return it return self.fromutc(dt) ``` ```python def localize(self, dt, is_dst=False): '''Convert naive time to local time. ... ''' if dt.tzinfo is not None: raise ValueError('Not naive datetime (tzinfo is already set)') ... ``` ```python def utcoffset(self, dt, is_dst=None): '''See datetime.tzinfo.utcoffset The is_dst parameter may be used to remove ambiguity during DST transitions. ... ''' if dt is None: return None elif dt.tzinfo is not self: dt = self.localize(dt, is_dst) return dt.tzinfo._utcoffset else: return self._utcoffset ``` ```python def dst(self, dt, is_dst=None): '''See datetime.tzinfo.dst ... ''' if dt is None: return None elif dt.tzinfo is not self: dt = self.localize(dt, is_dst) return dt.tzinfo._dst else: return self._dst ``` ```python def tzname(self, dt, is_dst=None): '''See datetime.tzinfo.tzname ... ''' if dt is None: return self.zone elif dt.tzinfo is not self: dt = self.localize(dt, is_dst) return dt.tzinfo._tzname else: return self._tzname ``` ```python def __repr__(self): if self._dst: dst = 'DST' else: dst = 'STD' if self._utcoffset > _notime: return '' % ( self.zone, self._tzname, self._utcoffset, dst ) else: return '' % ( self.zone, self._tzname, self._utcoffset, dst ) ``` ```python def __reduce__(self): # Special pickle to zone remains a singleton and to cope with # database changes. return pytz._p, ( self.zone, _to_seconds(self._utcoffset), _to_seconds(self._dst), self._tzname ) ``` -------------------------------- ### AmbiguousTimeError when is_dst omitted Source: https://github.com/stub42/pytz/blob/master/src/README.rst Shows that omitting is_dst on ambiguous timestamps raises pytz.exceptions.AmbiguousTimeError. The example demonstrates the exception for utcoffset(), dst(), and tzname() on the ambiguous datetime. ```python >>> print(tz.utcoffset(normal)) -1 day, 21:30:00 >>> print(tz.dst(normal)) 1:00:00 >>> tz.tzname(normal) 'NDT' ``` ```python >>> import pytz.exceptions >>> try: ... tz.utcoffset(ambiguous) ... except pytz.exceptions.AmbiguousTimeError: ... print('pytz.exceptions.AmbiguousTimeError: %s' % ambiguous) pytz.exceptions.AmbiguousTimeError: 2009-10-31 23:30:00 >>> try: ... tz.dst(ambiguous) ... except pytz.exceptions.AmbiguousTimeError: ... print('pytz.exceptions.AmbiguousTimeError: %s' % ambiguous) pytz.exceptions.AmbiguousTimeError: 2009-10-31 23:30:00 >>> try: ... tz.tzname(ambiguous) ... except pytz.exceptions.AmbiguousTimeError: ... print('pytz.exceptions.AmbiguousTimeError: %s' % ambiguous) pytz.exceptions.AmbiguousTimeError: 2009-10-31 23:30:00 ``` -------------------------------- ### DstTzInfo.fromutc Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/tzinfo.md Documentation for the DstTzInfo.fromutc method. ```APIDOC ## DstTzInfo.fromutc ### Description Converts an aware UTC datetime to a local aware datetime by finding the correct transition state and applying its offset and tzinfo. ### Method fromutc ### Signature fromutc(self, dt) ### Parameters - **dt** (datetime) - Required - An aware datetime in UTC. ### Returns - Local aware datetime with the appropriate offset and tzinfo. ### Throws - ValueError if dt.tzinfo is set and its _tzinfos registry differs from self. ``` -------------------------------- ### Get country timezones with pytz.country_timezones Source: https://github.com/stub42/pytz/blob/master/src/README.rst Retrieves the list of timezone names for a country using its ISO 3166 country code. The result is a list of strings that can be used with pytz.timezone(). ```python >>> print(' '.join(pytz.country_timezones['nz'])) Pacific/Auckland Pacific/Chatham ``` -------------------------------- ### Parse zone.tab record in _CountryTimezoneDict._fill Source: https://github.com/stub42/pytz/blob/master/_autodocs/types.md Parses one zone.tab record. Splits the line into code, coordinates, and zone; comment lines starting with '#' are skipped. The zone is retained only if it is in all_timezones_set. ```python code, coordinates, zone = line.split(None, 4)[:3] ``` -------------------------------- ### Convert timezones with astimezone Source: https://github.com/stub42/pytz/blob/master/src/README.rst Shows converting between timezones using the standard astimezone method. The example converts a UTC datetime to Australia/Sydney and back, demonstrating that the original and converted datetimes are equal. ```python >>> utc_dt = datetime.fromtimestamp(1143408899, tz=utc) >>> utc_dt.strftime(fmt) '2006-03-26 21:34:59 UTC+0000' >>> au_tz = timezone('Australia/Sydney') >>> au_dt = utc_dt.astimezone(au_tz) >>> au_dt.strftime(fmt) '2006-03-27 08:34:59 AEDT+1100' >>> utc_dt2 = au_dt.astimezone(utc) >>> utc_dt2.strftime(fmt) '2006-03-26 21:34:59 UTC+0000' >>> utc_dt == utc_dt2 True ``` -------------------------------- ### StaticTzInfo methods implementation Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/tzinfo.md Method implementations for StaticTzInfo, including fromutc, utcoffset, dst, tzname, localize, normalize, __repr__, and __reduce__. These methods handle timezone conversions and pickling. ```python def fromutc(self, dt): '''See datetime.tzinfo.fromutc''' if dt.tzinfo is not None and dt.tzinfo is not self: raise ValueError('fromutc: dt.tzinfo is not self') return (dt + self._utcoffset).replace(tzinfo=self) def utcoffset(self, dt, is_dst=None): '''See datetime.tzinfo.utcoffset is_dst is ignored for StaticTzInfo, and exists only to retain compatibility with DstTzInfo. ''' return self._utcoffset def dst(self, dt, is_dst=None): '''See datetime.tzinfo.dst is_dst is ignored for StaticTzInfo, and exists only to retain compatibility with DstTzInfo. ''' return _notime def tzname(self, dt, is_dst=None): '''See datetime.tzinfo.tzname is_dst is ignored for StaticTzInfo, and exists only to retain compatibility with DstTzInfo. ''' return self._tzname def localize(self, dt, is_dst=False): '''Convert naive time to local time''' if dt.tzinfo is not None: raise ValueError('Not naive datetime (tzinfo is already set)') return dt.replace(tzinfo=self) def normalize(self, dt, is_dst=False): '''Correct the timezone information on the given datetime. ... ''' if dt.tzinfo is self: return dt if dt.tzinfo is None: raise ValueError('Naive time - no tzinfo set') return dt.astimezone(self) def __repr__(self): return '' % (self.zone,) def __reduce__(self): # Special pickle to zone remains a singleton and to cope with # database changes. return pytz._p, (self.zone,) ``` -------------------------------- ### Normalize datetime across DST transition Source: https://github.com/stub42/pytz/blob/master/src/README.rst Shows how to normalize a datetime across a DST transition using eastern.normalize(). The example uses a datetime before the transition and demonstrates the resulting offset change. ```python >>> before = loc_dt - timedelta(minutes=10) >>> before.strftime(fmt) '2002-10-27 00:50:00 EST-0500' >>> eastern.normalize(before).strftime(fmt) '2002-10-27 01:50:00 EDT-0400' >>> after = eastern.normalize(before + timedelta(minutes=20)) >>> after.strftime(fmt) '2002-10-27 01:10:00 EST-0500' ``` -------------------------------- ### Parse iso3166.tab record in _CountryNameDict._fill Source: https://github.com/stub42/pytz/blob/master/_autodocs/types.md Parses one iso3166.tab record. Splits the line into code and name, then stores the name with trailing whitespace stripped. Comment lines starting with '#' are skipped. ```python code, name = line.split(None, 1) data[code] = name.strip() ``` -------------------------------- ### Get country timezones with country_timezones() Source: https://github.com/stub42/pytz/blob/master/src/README.rst Retrieves timezone lists for a country using the country_timezones() function, which accepts an ISO-3166 two-letter country code. The function is case-insensitive, as 'ch' and 'CH' both return 'Europe/Zurich'. ```python >>> from pytz import country_timezones >>> print(' '.join(country_timezones('ch'))) Europe/Zurich >>> print(' '.join(country_timezones('CH'))) Europe/Zurich ``` -------------------------------- ### open_resource(name) Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/pytz.md Opens a resource from the zoneinfo subdirectory for reading, with fallback mechanisms and environment variable override. ```APIDOC ## open_resource(name) ### Description Opens a resource from the zoneinfo subdirectory for reading. It uses the pkg_resources module if available and no standard file is found at the calculated location. The PYTZ_TZDATADIR environment variable can specify a different location for the zoneinfo subdirectory. ### Method Function ### Signature `open_resource(name)` ### Parameters - **name** (string) - Required - The resource name, e.g., 'US/Eastern'. Path segments must not be '..' or contain the OS path separator. ### Return Value Binary file object opened in read mode ('rb'). ### Exceptions - `ValueError` - If a path segment is `os.path.pardir` ('..') or contains the OS path separator. - `IOError`/`FileNotFoundError` - If the resource cannot be located by any mechanism. ### Resource Resolution Order 1. `PYTZ_TZDATADIR` environment variable overrides the base directory. 2. `/zoneinfo/` on disk. 3. `importlib.resources.files('pytz').joinpath('zoneinfo', ...)`. 4. `pkg_resources.resource_stream('pytz', 'zoneinfo/' + name)`. ### Example ```python import pytz fp = pytz.open_resource('US/Eastern') # binary file object over the zone file data = fp.read(4) # b'TZif' fp.close() ``` ``` -------------------------------- ### Using pytz.timezone to get timezone objects Source: https://github.com/stub42/pytz/blob/master/_autodocs/api-reference/pytz.md Demonstrates creating timezone objects with pytz.timezone, including the UTC short-circuit, case-insensitive lookup, and munged-name support. The last call raises an UnknownTimeZoneError because 'US/Eastern_plus_' is not a valid zone. ```python from pytz import timezone, utc eastern = timezone('US/Eastern') # DstTzInfo instance eastern.zone # 'US/Eastern' assert timezone('UTC') is utc # 'UTC' short-circuit, cached singleton assert timezone('us/eastern') is eastern # case-insensitive lookup + cache assert timezone('US/Eastern_plus_') # munged-name support (no such zone → raises) ``` -------------------------------- ### Localize ambiguous datetime without is_dst Source: https://github.com/stub42/pytz/blob/master/src/README.rst Shows that localizing an ambiguous datetime without is_dst makes an educated guess, resulting in a 50% chance of being off by one hour. The example uses the US/Eastern timezone on the last Sunday in October. ```python >>> loc_dt = eastern.localize(datetime(2002, 10, 27, 1, 30, 00)) >>> loc_dt.strftime(fmt) '2002-10-27 01:30:00 EST-0500' ```