2 min read

Python Zoneinfo Module

The zoneinfo module provides a concrete time zone implementation to support the IANA time zone database. It was introduced in Python 3.9 to replace the need for third-party libraries like pytz for most use cases.

Importing the Module

from zoneinfo import ZoneInfo

Basic Usage

To use a time zone, you create an instance of ZoneInfo with the key of the time zone (e.g., "America/New_York", "Europe/London", "UTC").

from zoneinfo import ZoneInfo
from datetime import datetime

# Create a datetime object with a specific time zone
dt = datetime(2023, 10, 31, 12, 0, 0, tzinfo=ZoneInfo("America/Los_Angeles"))
print(dt)
# Output: 2023-10-31 12:00:00-07:00

Converting Time Zones

You can convert a timezone-aware datetime object to another time zone using astimezone().

# Convert to UTC
dt_utc = dt.astimezone(ZoneInfo("UTC"))
print(dt_utc)
# Output: 2023-10-31 19:00:00+00:00

# Convert to Tokyo time
dt_tokyo = dt.astimezone(ZoneInfo("Asia/Tokyo"))
print(dt_tokyo)
# Output: 2023-11-01 04:00:00+09:00

Available Time Zones

You can get a set of all available time zones using zoneinfo.available_timezones().

import zoneinfo

available = zoneinfo.available_timezones()
print(f"Number of available time zones: {len(available)}")

if "Europe/Paris" in available:
    print("Europe/Paris is available")

Data Source

By default, zoneinfo uses the system's time zone data. If no system data is available (e.g., on Windows), it looks for the tzdata package from PyPI.

pip install tzdata

programming/python/python