Typing Stubs for pytz
types-pytz provides static type checking annotations (typing stubs) for the `pytz` library. It enables type checkers like MyPy and Pyright to analyze code that uses `pytz` for timezone operations, helping to catch type-related errors before runtime. As of its latest version `2026.1.1.20260304`, it aims to provide accurate annotations for `pytz==2026.1.post1` and is part of the actively maintained Typeshed project, which releases updates frequently.
Warnings
- gotcha The `types-pytz` package only provides typing stubs and does NOT install the actual `pytz` runtime library. You must explicitly install `pytz` (e.g., `pip install pytz`) for your code to run, in addition to `types-pytz` for type checking.
- gotcha For Python 3.9 and later, the built-in `zoneinfo` module (part of the standard library) is generally preferred over `pytz` for timezone handling. `zoneinfo` offers better integration with `datetime`, more intuitive API, and avoids some of `pytz`'s historical complexities and potential issues (e.g., the 2038 bug).
- gotcha When localizing naive `datetime` objects with `pytz`, it's crucial to use the `.localize()` method of a `pytz` timezone object (e.g., `tz.localize(naive_dt)`). Directly assigning a `pytz` timezone object to a `datetime`'s `tzinfo` attribute (e.g., `naive_dt.replace(tzinfo=tz)`) is often incorrect and can lead to `AmbiguousTimeError`, `NonExistentTimeError`, or subtle shifts to incorrect historical offsets like Local Mean Time (LMT).
- gotcha The `types-pytz` package is developed and released to provide accurate type annotations for specific versions of the `pytz` library. Mismatches between the installed `types-pytz` version and the `pytz` runtime version can lead to incorrect type-checking results (e.g., missing attributes or wrong argument types).
Install
-
pip install types-pytz
Imports
- timezone
from pytz import timezone
- utc
from pytz import utc
- DstTzInfo
from pytz.tzinfo import DstTzInfo
Quickstart
from datetime import datetime
from pytz import timezone, utc
# Create a naive datetime object
naive_dt = datetime(2024, 7, 21, 10, 30, 0)
print(f"Naive Datetime: {naive_dt}")
# Get a timezone object
eastern = timezone('America/New_York')
# Localize the naive datetime (make it timezone-aware)
aware_dt_eastern = eastern.localize(naive_dt)
print(f"Aware Datetime (Eastern): {aware_dt_eastern}")
# Convert to UTC
aware_dt_utc = aware_dt_eastern.astimezone(utc)
print(f"Aware Datetime (UTC): {aware_dt_utc}")
# Get current time in a specific timezone
current_paris_time = datetime.now(timezone('Europe/Paris'))
print(f"Current Paris Time: {current_paris_time}")
def get_current_utc() -> datetime:
"""Returns the current UTC time with timezone awareness."""
return datetime.now(utc)
# Demonstrate type checking with a function call
current_utc = get_current_utc()
print(f"Current UTC (from typed function): {current_utc}")