🔥 HOT: /library/zoneinfo.html - Collection
zoneinfo — IANA time zone support¶
Added in version 3.9.
Source code: Lib/zoneinfo
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-party tzdata package available on PyPI.
See also
Availability: not WASI.
This module does not work or is not available on WebAssembly. See WebAssembly platforms for more information.
Using ZoneInfo¶
ZoneInfo is a concrete implementation of the datetime.tzinfo
abstract base class, and is intended to be attached to tzinfo, either via
the constructor, the datetime.replace
method or datetime.astimezone:
>>> from zoneinfo import ZoneInfo
>>> from datetime import datetime, timedelta
>>> dt = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles"))
>>> print(dt)
2020-10-31 12:00:00-07:00
>>> dt.tzname()
'PDT'
Datetimes constructed in this way are compatible with datetime arithmetic and handle daylight saving time transitions with no further intervention:
>>> dt_add = dt + timedelta(days=1)
>>> print(dt_add)
2020-11-01 12:00:00-08:00
>>> dt_add.tzname()
'PST'
These time zones also support the fold attribute
introduced in PEP 495. During offset transitions which induce ambiguous
times (such as a daylight saving time to standard time transition), the offset
from before the transition is used when fold=0, and the offset after
the transition is used when fold=1, for example:
>>> dt = datetime(2020, 11, 1, 1, tzinfo=ZoneInfo("America/Los_Angeles"))
>>> print(dt)
2020-11-01 01:00:00-07:00
>>> print(dt.replace(fold=1))
2020-11-01 01:00:00-08:00
When converting from another time zone, the fold will be set to the correct value:
>>> from datetime import timezone
>>> LOS_ANGELES = ZoneInfo("America/Los_Angeles")
>>> dt_utc = datetime(2020, 11, 1, 8, tzinfo=timezone.utc)
>>> # Before the PDT -> PST transition
>>> print(dt_utc.astimezone(LOS_ANGELES))
2020-11-01 01:00:00-07:00
>>> # After the PDT -> PST transition
>>> print((dt_utc + timedelta(hours=1)).astimezone(LOS_ANGELES))
2020-11-01 01:00:00-08:00
Data sources¶
The zoneinfo module does not directly provide time zone data, and instead
pulls time zone information from the system time zone database or the
first-party PyPI package tzdata, if available. Some systems, including
notably Windows systems, do not have an IANA database available, and so for
projects targeting cross-platform compatibility that require time zone data, it
is recommended to declare a dependency on tzdata. If neither system data nor
tzdata are available, all calls to ZoneInfo will raise
ZoneInfoNotFoundError.
Configuring the data sources¶
When ZoneInfo(key) is called, the constructor first searches the
directories specified in TZPATH for a file matching key, and on
failure looks for a match in the tzdata package. This behavior can be
configured in three ways:
The default
TZPATHwhen not otherwise specified can be configured at compile time.TZPATHcan be configured using an environment variable.At runtime, the search path can be manipulated using the
reset_tzpath()function.
Compile-time configuration¶
The default TZPATH includes several common deployment locations for the
time zone database (except on Windows, where there are no “well-known”
locations for time zone data). On POSIX systems, downstream distributors and
those building Python from source who know where their system
time zone data is deployed may change the default time zone path by specifying
the compile-time option TZPATH (or, more likely, the configure
flag --with-tzpath), which should be a string delimited by
os.pathsep.
On all platforms, the configured value is available as the TZPATH key in
sysconfig.get_config_var().
Environment configuration¶
When initializing TZPATH (either at import time or whenever
reset_tzpath() is called with no arguments), the zoneinfo module will
use the environment variable PYTHONTZPATH, if it exists, to set the search
path.
- PYTHONTZPATH¶
This is an
os.pathsep-separated string containing the time zone search path to use. It must consist of only absolute rather than relative paths. Relative components specified inPYTHONTZPATHwill not be used, but otherwise the behavior when a relative path is specified is implementation-defined; CPython will raiseInvalidTZPathWarning, but other implementations are free to silently ignore the erroneous component or raise an exception.
To set the system to ignore the system data and use the tzdata package
instead, set PYTHONTZPATH="".
Runtime configuration¶
The TZ search path can also be configured at runtime using the
reset_tzpath() function. This is generally not an advisable operation,
though it is reasonable to use it in test functions that require the use of a
specific time zone path (or require disabling access to the system time zones).
The ZoneInfo class¶
- class zoneinfo.ZoneInfo(key)¶
A concrete
datetime.tzinfosubclass that represents an IANA time zone specified by the stringkey. Calls to the primary constructor will always return objects that compare identically; put another way, barring cache invalidation viaZoneInfo.clear_cache(), for all values ofkey, the following assertion will always be true:a = ZoneInfo(key) b = ZoneInfo(key) assert a is b
keymust be in the form of a relative, normalized POSIX path, with no up-level references. The constructor will raiseValueErrorif a non-conforming key is passed.If no file matching
keyis found, the constructor will raiseZoneInfoNotFoundError.
The ZoneInfo class has two alternate constructors:
- classmethod ZoneInfo.from_file(file_obj, /, key=None)¶
Constructs a
ZoneInfoobject from a file-like object returning bytes (e.g. a file opened in binary mode or anio.BytesIOobject). Unlike the primary constructor, this always constructs a new object.The
keyparameter sets the name of the zone for the purposes of__str__()and__repr__()