zoneinfo --- IANA 時區支援

在 3.9 版被加入.

原始碼:Lib/zoneinfo


Thezoneinfo module provides a concrete time zone implementation tosupport the IANA time zone database as originally specified inPEP 615. Bydefault,zoneinfo uses the system's time zone data if available; if nosystem time zone data is available, the library will fall back to using thefirst-partytzdata package available on PyPI.

也參考

datetime 模組

Provides thetime anddatetimetypes with which theZoneInfo class is designed to be used.

tzdata 套件

First-party package maintained by the CPython core developers to supplytime zone data via PyPI.

適用: not WASI.

此模組在 WebAssembly 平台上不起作用或無法使用。更多資訊請參閱WebAssembly 平台

UsingZoneInfo

ZoneInfo is a concrete implementation of thedatetime.tzinfoabstract base class, and is intended to be attached totzinfo, either viathe constructor, thedatetime.replacemethod ordatetime.astimezone:

>>>fromzoneinfoimportZoneInfo>>>fromdatetimeimportdatetime,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 andhandle 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 thefold attributeintroduced inPEP 495. During offset transitions which induce ambiguoustimes (such as a daylight saving time to standard time transition), the offsetfrombefore the transition is used whenfold=0, and the offsetafterthe transition is used whenfold=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 correctvalue:

>>>fromdatetimeimporttimezone>>>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

Thezoneinfo module does not directly provide time zone data, and insteadpulls time zone information from the system time zone database or thefirst-party PyPI packagetzdata, if available. Some systems, includingnotably Windows systems, do not have an IANA database available, and so forprojects targeting cross-platform compatibility that require time zone data, itis recommended to declare a dependency on tzdata. If neither system data nortzdata are available, all calls toZoneInfo will raiseZoneInfoNotFoundError.

Configuring the data sources

WhenZoneInfo(key) is called, the constructor first searches thedirectories specified inTZPATH for a file matchingkey, and onfailure looks for a match in the tzdata package. This behavior can beconfigured in three ways:

  1. The defaultTZPATH when not otherwise specified can be configured atcompile time.

  2. TZPATH can be configured usingan environment variable.

  3. Atruntime, the search path can bemanipulated using thereset_tzpath() function.

Compile-time configuration

The defaultTZPATH includes several common deployment locations for thetime zone database (except on Windows, where there are no "well-known"locations for time zone data). On POSIX systems, downstream distributors andthose building Python from source who know where their systemtime zone data is deployed may change the default time zone path by specifyingthe compile-time optionTZPATH (or, more likely, theconfigureflag--with-tzpath), which should be a string delimited byos.pathsep.

On all platforms, the configured value is available as theTZPATH key insysconfig.get_config_var().

Environment configuration

When initializingTZPATH (either at import time or wheneverreset_tzpath() is called with no arguments), thezoneinfo module willuse the environment variablePYTHONTZPATH, if it exists, to set the searchpath.

PYTHONTZPATH

This is anos.pathsep-separated string containing the time zonesearch path to use. It must consist of only absolute rather than relativepaths. Relative components specified inPYTHONTZPATH will not be used,but otherwise the behavior when a relative path is specified isimplementation-defined; CPython will raiseInvalidTZPathWarning, butother implementations are free to silently ignore the erroneous componentor raise an exception.

To set the system to ignore the system data and use the tzdata packageinstead, setPYTHONTZPATH="".

Runtime configuration

The TZ search path can also be configured at runtime using thereset_tzpath() function. This is generally not an advisable operation,though it is reasonable to use it in test functions that require the use of aspecific time zone path (or require disabling access to the system time zones).

TheZoneInfo class

classzoneinfo.ZoneInfo(key)

A concretedatetime.tzinfo subclass that represents an IANA timezone specified by the stringkey. Calls to the primary constructor willalways return objects that compare identically; put another way, barringcache invalidation viaZoneInfo.clear_cache(), for all values ofkey, the following assertion will always be true:

a=ZoneInfo(key)b=ZoneInfo(key)assertaisb

key must be in the form of a relative, normalized POSIX path, with noup-level references. The constructor will raiseValueError if anon-conforming key is passed.

If no file matchingkey is found, the constructor will raiseZoneInfoNotFoundError.

TheZoneInfo class has two alternate constructors:

classmethodZoneInfo.from_file(fobj,/,key=None)

Constructs aZoneInfo object from a file-like object returning bytes(e.g. a file opened in binary mode or anio.BytesIO object).Unlike the primary constructor, this always constructs a new object.

Thekey parameter sets the name of the zone for the purposes of__str__() and__repr__().

Objects created via this constructor cannot be pickled (seepickling).

classmethodZoneInfo.no_cache(key)

An alternate constructor that bypasses the constructor's cache. It isidentical to the primary constructor, but returns a new object on eachcall. This is most likely to be useful for testing or demonstrationpurposes, but it can also be used to create a system with a different cacheinvalidation strategy.

Objects created via this constructor will also bypass the cache of adeserializing process when unpickled.

警示

Using this constructor may change the semantics of your datetimes insurprising ways, only use it if you know that you need to.

The following class methods are also available:

classmethodZoneInfo.clear_cache(*,only_keys=None)

A method for invalidating the cache on theZoneInfo class. If noarguments are passed, all caches are invalidated and the next call tothe primary constructor for each key will return a new instance.

If an iterable of key names is passed to theonly_keys parameter, onlythe specified keys will be removed from the cache. Keys passed toonly_keys but not found in the cache are ignored.

警告

Invoking this function may change the semantics of datetimes usingZoneInfo in surprising ways; this modifies module stateand thus may have wide-ranging effects. Only use it if you know that youneed to.

The class has one attribute:

ZoneInfo.key

This is a read-onlyattribute that returns the value ofkeypassed to the constructor, which should be a lookup key in the IANA timezone database (e.g.America/New_York,Europe/Paris orAsia/Tokyo).

For zones constructed from file without specifying akey parameter,this will be set toNone.

備註

Although it is a somewhat common practice to expose these to end users,these values are designed to be primary keys for representing therelevant zones and not necessarily user-facing elements. Projects likeCLDR (the Unicode Common Locale Data Repository) can be used to getmore user-friendly strings from these keys.

String representations

The string representation returned when callingstr on aZoneInfo object defaults to using theZoneInfo.key attribute (seethe note on usage in the attribute documentation):

>>>zone=ZoneInfo("Pacific/Kwajalein")>>>str(zone)'Pacific/Kwajalein'>>>dt=datetime(2020,4,1,3,15,tzinfo=zone)>>>f"{dt.isoformat()} [{dt.tzinfo}]"'2020-04-01T03:15:00+12:00 [Pacific/Kwajalein]'

For objects constructed from a file without specifying akey parameter,str falls back to callingrepr().ZoneInfo'srepr isimplementation-defined and not necessarily stable between versions, but it isguaranteed not to be a validZoneInfo key.

Pickle serialization

Rather than serializing all transition data,ZoneInfo objects areserialized by key, andZoneInfo objects constructed from files (even thosewith a value forkey specified) cannot be pickled.

The behavior of aZoneInfo file depends on how it was constructed:

  1. ZoneInfo(key): When constructed with the primary constructor, aZoneInfo object is serialized by key, and when deserialized, thedeserializing process uses the primary and thus it is expected that theseare expected to be the same object as other references to the same timezone. For example, ifeurope_berlin_pkl is a string containing a pickleconstructed fromZoneInfo("Europe/Berlin"), one would expect thefollowing behavior:

    >>>a=ZoneInfo("Europe/Berlin")>>>b=pickle.loads(europe_berlin_pkl)>>>aisbTrue
  2. ZoneInfo.no_cache(key): When constructed from the cache-bypassingconstructor, theZoneInfo object is also serialized by key, but whendeserialized, the deserializing process uses the cache bypassingconstructor. Ifeurope_berlin_pkl_nc is a string containing a pickleconstructed fromZoneInfo.no_cache("Europe/Berlin"), one would expectthe following behavior:

    >>>a=ZoneInfo("Europe/Berlin")>>>b=pickle.loads(europe_berlin_pkl_nc)>>>aisbFalse
  3. ZoneInfo.from_file(fobj,/,key=None): When constructed from a file, theZoneInfo object raises an exception on pickling. If an end user wants topickle aZoneInfo constructed from a file, it is recommended that theyuse a wrapper type or a custom serialization function: either serializing bykey or storing the contents of the file object and serializing that.

This method of serialization requires that the time zone data for the requiredkey be available on both the serializing and deserializing side, similar to theway that references to classes and functions are expected to exist in both theserializing and deserializing environments. It also means that no guaranteesare made about the consistency of results when unpickling aZoneInfopickled in an environment with a different version of the time zone data.

函式

zoneinfo.available_timezones()

Get a set containing all the valid keys for IANA time zones availableanywhere on the time zone path. This is recalculated on every call to thefunction.

This function only includes canonical zone names and does not include"special" zones such as those under theposix/ andright/directories, or theposixrules zone.

警示

This function may open a large number of files, as the best way todetermine if a file on the time zone path is a valid time zone is toread the "magic string" at the beginning.

備註

These values are not designed to be exposed to end-users; for userfacing elements, applications should use something like CLDR (theUnicode Common Locale Data Repository) to get more user-friendlystrings. See also the cautionary note onZoneInfo.key.

zoneinfo.reset_tzpath(to=None)

Sets or resets the time zone search path (TZPATH) for the module.When called with no arguments,TZPATH is set to the default value.

Callingreset_tzpath will not invalidate theZoneInfo cache,and so calls to the primaryZoneInfo constructor will only use the newTZPATH in the case of a cache miss.

Theto parameter must be asequence of strings oros.PathLike and not a string, all of which must be absolute paths.ValueError will be raised if something other than an absolute pathis passed.

Globals

zoneinfo.TZPATH

A read-only sequence representing the time zone search path -- whenconstructing aZoneInfo from a key, the key is joined to each entry intheTZPATH, and the first file found is used.

TZPATH may contain only absolute paths, never relative paths,regardless of how it is configured.

The object thatzoneinfo.TZPATH points to may change in response to acall toreset_tzpath(), so it is recommended to usezoneinfo.TZPATH rather than importingTZPATH fromzoneinfo orassigning a long-lived variable tozoneinfo.TZPATH.

For more information on configuring the time zone search path, seeConfiguring the data sources.

Exceptions and warnings

exceptionzoneinfo.ZoneInfoNotFoundError

Raised when construction of aZoneInfo object fails because thespecified key could not be found on the system. This is a subclass ofKeyError.

exceptionzoneinfo.InvalidTZPathWarning

Raised whenPYTHONTZPATH contains an invalid component that willbe filtered out, such as a relative path.