Python 3.9 introduced the zoneinfo
module:
The
zoneinfo
module provides a concrete time zone implementation to support the IANA time zone database as originally specified in PEP 615. By default,zoneinfo
uses the system’s time zone data if available; if no system time zone data is available, the library will fall back to using the first-partytzdata
package available on PyPI.
On my Ubuntu machine, it supports lots of time zones:
>>> from zoneinfo import ZoneInfo
>>> ZoneInfo("America/New_York")
zoneinfo.ZoneInfo(key='America/New_York')
>>> ZoneInfo("MST") # Mountain Standard Time
zoneinfo.ZoneInfo(key='MST')
>>> ZoneInfo("CET") # Central European Time
zoneinfo.ZoneInfo(key='CET')
However, it doesn't seem to support some time zones abbreviations used in North America like Central Time (CT), Central Standard Time (CST) or Pacific Standard Time (PST).
>>> ZoneInfo("CT")
zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key CT'
>>> ZoneInfo("CST")
zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key CST'
>>> ZoneInfo("PST")
zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key PST'
How can I get the right ZoneInfo
objects for time zones like CT, CST or PST? Is the time zone database lacking? Does it depend on the operating system that I'm running?
There are issues with the abbreviations CT (Central Time), CST (Central Standard Time), PT (Pacific Time), and PST (Pacific Standard Time). Here are the main two:
Instead of CT (CST during the winter or CDT during the summer), use US/Central
or Canada/Central
IANA identifier instead:
>>> from zoneinfo import ZoneInfo
>>> ZoneInfo("US/Central")
zoneinfo.ZoneInfo(key='US/Central')
Instead of PT (PST during the winter or PDT during the summer), use US/Pacific
or Canada/Pacific
instead:
>>> ZoneInfo("US/Pacific")
zoneinfo.ZoneInfo(key='US/Pacific')
For MT (MST during the winter and MDT during the summer), use US/Mountain
for the areas that follow daylight savings time during the summer, and use America/Phoenix
for the parts of Arizona that use MST all year round.
>>> ZoneInfo("US/Mountain")
zoneinfo.ZoneInfo(key='US/Mountain')
>>> ZoneInfo("America/Phoenix")
zoneinfo.ZoneInfo(key='America/Phoenix')
Note that Python does accept MST
as a key. This identifier does not follow daylight savings time though, which you may not expect.
For ET (EST during the winter or EDT during the summer), use US/Eastern
or Canada/Eastern
:
>>> from zoneinfo import ZoneInfo
>>> ZoneInfo("US/Eastern")
zoneinfo.ZoneInfo(key='US/Eastern')
Note that Python does accept EST
as a key. This identifier does not follow daylight savings time though, which you may not expect.
(Notice that parts of Arizona on the map represented by Phoenix don't observe Daylight Time)