pytz-deprecation-shim
pytz-deprecation-shim provides compatibility shims to ease the migration away from the `pytz` library to PEP 495-compatible time zone implementations like the standard library's `zoneinfo` (Python 3.9+) or `python-dateutil`. It allows existing codebases to gradually deprecate `pytz`-specific interfaces while ensuring continued functionality. The current version is 0.1.0.post0, with the last release in June 2020.
Warnings
- breaking This library is intended for *temporary* usage during the migration from `pytz`. Your ultimate goal should be to remove this shim and directly use standard library `zoneinfo` (Python 3.9+) or `python-dateutil`.
- gotcha Avoid calling `localize()` or `normalize()` methods directly on time zone objects returned by `pytz_deprecation_shim`. While the shim provides these for backward compatibility, their use will raise `PytzUsageWarning` and indicates non-PEP 495 compliant behavior, which should be migrated away from.
- gotcha There is a performance overhead associated with using `pytz-deprecation-shim` compared to using the underlying `zoneinfo` or `dateutil.tz` libraries directly, as it involves an additional layer of wrapping.
- gotcha Datetime arithmetic using `pytz_deprecation_shim` objects will follow PEP 495 'wall time' semantics, which differs from `pytz`'s 'add-and-normalize' (absolute time) workflow. This can lead to subtle differences in results, especially across daylight saving time transitions.
- deprecated The `pytz` library itself is considered deprecated, with `zoneinfo` (Python 3.9+) and `python-dateutil` being the recommended replacements. `pytz-deprecation-shim` exists *because* `pytz` is deprecated.
Install
-
pip install pytz-deprecation-shim
Imports
- timezone
from pytz_deprecation_shim import timezone
- UTC
from pytz_deprecation_shim import UTC
- PytzUsageWarning
from pytz_deprecation_shim import PytzUsageWarning
Quickstart
import pytz_deprecation_shim as pds
from datetime import datetime
# Get a timezone using the shim (behaves like zoneinfo/dateutil.tz)
LA = pds.timezone("America/Los_Angeles")
# Create an aware datetime by directly attaching the tzinfo
dt = datetime(2020, 10, 31, 12, tzinfo=LA)
print(f"Aware datetime: {dt}")
print(f"Timezone name: {dt.tzname()}")
# The shim can also wrap existing PEP 495-compatible time zones
# from datetime.zoneinfo (Python 3.9+) or dateutil.tz
try:
from zoneinfo import ZoneInfo
NYC_zoneinfo = ZoneInfo("America/New_York")
NYC_shim = pds.wrap_zone(NYC_zoneinfo, key="America/New_York")
dt_nyc = datetime(2023, 7, 15, 10, tzinfo=NYC_shim)
print(f"Wrapped ZoneInfo datetime: {dt_nyc}")
except ImportError:
print("zoneinfo not available (Python < 3.9 or backport not installed)")