Python’s zoneinfo module, introduced in Python 3.9, offers a robust solution for dealing with time zones. It provides access to the IANA time zone database, which is the industry standard for time zone information. Here’s how you can use the zoneinfo module in your Python applications.
Installation and Import
The zoneinfo module is available in Python 3.9 and later versions. Make sure your Python version meets this requirement before importing the zoneinfo module:
from zoneinfo import ZoneInfo
Basic Usage
Assign a time zone to a datetime object using the ZoneInfo class:
from datetime import datetime
from zoneinfo import ZoneInfo
# Here's how to create a datetime object with the 'America/New_York' time zone using the ZoneInfo class:
dt = datetime(2021, 10, 31, 12, tzinfo=ZoneInfo('America/New_York'))
Time Zone Conversion
Convert existing datetime objects to different time zones:
# To convert an existing datetime object to a different time zone, use the astimezone method with the desired ZoneInfo object:
dt_utc = dt.astimezone(ZoneInfo('UTC'))
Handling Daylight Saving Time
The zoneinfo module automatically handles daylight saving time transitions, adjusting times accordingly based on the specified time zone.
Accessing Time Zone Data
Retrieve and work with various attributes of time zones, such as offset, name, and more, to understand and manipulate time zone data accurately.