zoneinfoIANA time zone supportIANA时区支持

New in version 3.9.版本3.9中新增。


The zoneinfo module provides a concrete time zone implementation to support the IANA time zone database as originally specified in PEP 615. zoneinfo模块提供了一个具体的时区实现,以支持最初在PEP 615中指定的IANA时区数据库。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.默认情况下,zoneinfo使用系统的时区数据(如果可用);如果没有可用的系统时区数据,库将返回到使用PyPI上可用的第一方tzdata包。

See also另请参见

Module: 模块:datetime

Provides the time and datetime types with which the ZoneInfo class is designed to be used.提供ZoneInfo类设计用于的timedatetime类型。

Package tzdata

First-party package maintained by the CPython core developers to supply time zone data via PyPI.由CPython核心开发人员维护的第一方包,用于通过PyPI提供时区数据。

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:ZoneInfodatetime.tzinfo抽象基类的具体实现,旨在通过构造函数、datetime.replace方法或datetime.astimezone附加到tzinfo

>>> 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. 这些时区还支持PEP 495中引入的fold属性。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:在导致时间不明确的偏移转换期间(例如夏令时到标准时间的转换),当fold=0时使用转换前的偏移,当fold=1时使用转换后的偏移,例如:

>>> 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. zoneinfo模块不直接提供时区数据,而是从系统时区数据库或第一方PyPI包tzdata(如果可用)中提取时区信息。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. 一些系统,尤其是Windows系统,没有可用的IANA数据库,因此对于需要时区数据的跨平台兼容性项目,建议声明对tzdata的依赖关系。If neither system data nor tzdata are available, all calls to ZoneInfo will raise ZoneInfoNotFoundError.如果系统数据和tzdata都不可用,则对ZoneInfo的所有调用都将引发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. 调用ZoneInfo(key)时,构造函数首先搜索TZPATH中指定的目录以查找与键匹配的文件,失败时在tzdata包中查找匹配项。This behavior can be configured in three ways:可以通过三种方式配置此行为:

  1. The default TZPATH when not otherwise specified can be configured at compile time.如果未另行指定,则可以在编译时配置默认TZPATH

  2. TZPATH can be configured using an environment variable.可以使用环境变量配置TZPATH

  3. At runtime, the search path can be manipulated using the reset_tzpath() function.运行时,可以使用reset_tzpath()函数操纵搜索路径。

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). 默认TZPATH包括时区数据库的几个常见部署位置(Windows上除外,Windows上没有时区数据的“已知”位置)。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.在POSIX系统上,下游分发服务器和那些从源代码构建Python并知道其系统时区数据部署在何处的分发服务器可以通过指定编译时选项TZPATH(或者更可能的是,configure flag --with-tzpath)来更改默认时区路径,该选项应该是由os.pathsep分隔的字符串。

On all platforms, the configured value is available as the TZPATH key in sysconfig.get_config_var().在所有平台上,配置的值都可以作为sysconfig.get_config_var()中的TZPATH键使用。

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.初始化TZPATH时(无论是在导入时还是在没有参数的情况下调用reset_tzpath()时),zoneinfo模块将使用环境变量PYTHONTZPATH(如果存在)来设置搜索路径。

PYTHONTZPATH

This is an os.pathsep-separated string containing the time zone search path to use. 这是一个os.pathsep分隔字符串,包含要使用的时区搜索路径。It must consist of only absolute rather than relative paths. 它必须只包含绝对路径而不是相对路径。Relative components specified in PYTHONTZPATH will not be used, but otherwise the behavior when a relative path is specified is implementation-defined; CPython will raise InvalidTZPathWarning, but other implementations are free to silently ignore the erroneous component or raise an exception.不会使用PYTHONTZPATH中指定的相对组件,但在其他情况下,指定相对路径时的行为是由实现定义的;CPython将引发InvalidTZPathWarning,但其他实现可以自动忽略错误组件或引发异常。

To set the system to ignore the system data and use the tzdata package instead, set PYTHONTZPATH="".要将系统设置为忽略系统数据并改用tzdata包,请设置PYTHONTZPATH=""

Runtime configuration运行时配置

The TZ search path can also be configured at runtime using the reset_tzpath() function. TZ搜索路径也可以在运行时使用reset_tzpath()函数进行配置。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 classZoneInfo

classzoneinfo.ZoneInfo(key)

A concrete datetime.tzinfo subclass that represents an IANA time zone specified by the string key. 一个具体的datetime.tzinfo子类,表示由字符串key指定的IANA时区。Calls to the primary constructor will always return objects that compare identically; put another way, barring cache invalidation via ZoneInfo.clear_cache(), for all values of key, the following assertion will always be true:对主构造函数的调用将始终返回相同比较的对象;换句话说,除非通过ZoneInfo.clear_cache()使缓存无效,否则对于key的所有值,以下断言始终为真:

a = ZoneInfo(key)
b = ZoneInfo(key)
assert a is b

key must be in the form of a relative, normalized POSIX path, with no up-level references. key必须是相对的、规范化的POSIX路径,没有上层引用。The constructor will raise ValueError if a non-conforming key is passed.如果传递了不一致的密钥,构造函数将引发ValueError

If no file matching key is found, the constructor will raise ZoneInfoNotFoundError.如果没有找到文件匹配key,构造函数将引发ZoneInfoNotFoundError

The ZoneInfo class has two alternate constructors:ZoneInfo类有两个备用构造函数:

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

Constructs a ZoneInfo object from a file-like object returning bytes (e.g. a file opened in binary mode or an io.BytesIO object). 从返回字节的类文件对象(例如,以二进制模式打开的文件或io.BytesIO对象)构造ZoneInfo对象。Unlike the primary constructor, this always constructs a new object.与主构造函数不同,它总是构造一个新对象。

The key parameter sets the name of the zone for the purposes of __str__() and __repr__().键参数设置区域的名称,用于__str__()__repr__()的目的。

Objects created via this constructor cannot be pickled (see pickling).无法对通过此构造函数创建的对象进行pickle(请参阅pickle)。

classmethodZoneInfo.no_cache(key)

An alternate constructor that bypasses the constructor’s cache. 绕过构造函数缓存的备用构造函数。It is identical to the primary constructor, but returns a new object on each call. 它与主构造函数相同,但每次调用时都返回一个新对象。This is most likely to be useful for testing or demonstration purposes, but it can also be used to create a system with a different cache invalidation strategy.这很可能对测试或演示有用,但也可以用于创建具有不同缓存失效策略的系统。

Objects created via this constructor will also bypass the cache of a deserializing process when unpickled.当取消勾选时,通过此构造函数创建的对象也将绕过反序列化过程的缓存。

Caution小心

Using this constructor may change the semantics of your datetimes in surprising 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 the ZoneInfo class. 使ZoneInfo类上的缓存无效的方法。If no arguments are passed, all caches are invalidated and the next call to the primary constructor for each key will return a new instance.如果没有传递任何参数,则所有缓存都将无效,下一次调用每个键的主构造函数将返回一个新实例。

If an iterable of key names is passed to the only_keys parameter, only the specified keys will be removed from the cache. 如果将一组密钥名传递给only_keys参数,则只会从缓存中删除指定的密钥。Keys passed to only_keys but not found in the cache are ignored.仅传递给_键但未在缓存中找到的键将被忽略。

Warning

Invoking this function may change the semantics of datetimes using ZoneInfo in surprising ways; this modifies process-wide global state and thus may have wide-ranging effects. 调用此函数可能会以令人惊讶的方式更改使用ZoneInfo的日期时间的语义;这会修改进程范围内的全局状态,因此可能会产生广泛的影响。Only use it if you know that you need to.只有当你知道需要时才使用它。

The class has one attribute:该类有一个属性:

ZoneInfo.key

This is a read-only attribute that returns the value of key passed to the constructor, which should be a lookup key in the IANA time zone database (e.g. America/New_York, Europe/Paris or Asia/Tokyo).这是一个只读属性,返回传递给构造函数的key的值,该值应该是IANA时区数据库(例如,America/New_YorkEurope/ParisAsia/Tokyo)中的查找键。

For zones constructed from file without specifying a key parameter, this will be set to None.对于从文件构造的分区,如果未指定key参数,则该选项将设置为“无”。

Note

Although it is a somewhat common practice to expose these to end users, these values are designed to be primary keys for representing the relevant zones and not necessarily user-facing elements. 尽管向最终用户公开这些值是一种常见做法,但这些值被设计为表示相关区域的主键,而不一定是面向用户的元素。Projects like CLDR (the Unicode Common Locale Data Repository) can be used to get more user-friendly strings from these keys.像CLDR(Unicode公共区域设置数据存储库)这样的项目可以用于从这些键中获取更用户友好的字符串。

String representations字符串表示法

The string representation returned when calling str on a ZoneInfo object defaults to using the ZoneInfo.key attribute (see the note on usage in the attribute documentation):ZoneInfo对象上调用str时返回的字符串表示形式默认为使用ZoneInfo.key属性(请参阅属性文档中的用法说明):

>>> 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 a key parameter, str falls back to calling repr(). 对于从没有指定key参数的文件构造的对象,str返回到调用repr()ZoneInfo’s repr is implementation-defined and not necessarily stable between versions, but it is guaranteed not to be a valid ZoneInfo key.ZoneInforepr是实现定义的,在不同版本之间不一定稳定,但保证不是有效的ZoneInfo键。

Pickle serializationPickle序列化

Rather than serializing all transition data, ZoneInfo objects are serialized by key, and ZoneInfo objects constructed from files (even those with a value for key specified) cannot be pickled.ZoneInfo对象不是序列化所有转换数据,而是按键序列化,并且不能对从文件(甚至是指定了键值的文件)构造的ZoneInfo对象进行pickle。

The behavior of a ZoneInfo file depends on how it was constructed:ZoneInfo文件的行为取决于其构造方式:

  1. ZoneInfo(key): When constructed with the primary constructor, a ZoneInfo object is serialized by key, and when deserialized, the deserializing process uses the primary and thus it is expected that these are expected to be the same object as other references to the same time zone. :当使用主构造函数构造时,ZoneInfo对象按键序列化,当反序列化时,反序列化过程使用主构造函数,因此这些对象应与对同一时区的其他引用相同。For example, if europe_berlin_pkl is a string containing a pickle constructed from ZoneInfo("Europe/Berlin"), one would expect the following behavior:例如,如果europe_berlin_pkl是一个包含由ZoneInfo("Europe/Berlin")构造的pickle的字符串,则会出现以下行为:

    >>> a = ZoneInfo("Europe/Berlin")
    >>> b = pickle.loads(europe_berlin_pkl)
    >>> a is b
    True
  2. ZoneInfo.no_cache(key): When constructed from the cache-bypassing constructor, the ZoneInfo object is also serialized by key, but when deserialized, the deserializing process uses the cache bypassing constructor. :当从缓存绕过构造函数构造时,ZoneInfo对象也按键序列化,但当反序列化时,反序列化过程使用缓存绕过构造函数。If europe_berlin_pkl_nc is a string containing a pickle constructed from ZoneInfo.no_cache("Europe/Berlin"), one would expect the following behavior:如果europe_berlin_pkl_nc是一个包含由ZoneInfo.no_cache("Europe/Berlin")构造的pickle的字符串,则会出现以下行为:

    >>> a = ZoneInfo("Europe/Berlin")
    >>> b = pickle.loads(europe_berlin_pkl_nc)
    >>> a is b
    False
  3. ZoneInfo.from_file(fobj, /, key=None): When constructed from a file, the ZoneInfo object raises an exception on pickling. :从文件构造时,ZoneInfo对象在酸洗时引发异常。If an end user wants to pickle a ZoneInfo constructed from a file, it is recommended that they use a wrapper type or a custom serialization function: either serializing by key or storing the contents of the file object and serializing that.如果最终用户希望pickle从文件构造的ZoneInfo,建议他们使用包装类型或自定义序列化函数:按键序列化或存储文件对象的内容并序列化。

This method of serialization requires that the time zone data for the required key be available on both the serializing and deserializing side, similar to the way that references to classes and functions are expected to exist in both the serializing and deserializing environments. 这种序列化方法要求所需键的时区数据在序列化和反序列化侧都可用,类似于对类和函数的引用在序列化和反序列化环境中预期存在的方式。It also means that no guarantees are made about the consistency of results when unpickling a ZoneInfo pickled in an environment with a different version of the time zone data.这还意味着,在使用不同版本的时区数据的环境中,取消勾选经过酸洗的ZoneInfo时,无法保证结果的一致性。

Functions功能

zoneinfo.available_timezones()

Get a set containing all the valid keys for IANA time zones available anywhere on the time zone path. 获取一个集合,其中包含时区路径上任何位置可用的IANA时区的所有有效键。This is recalculated on every call to the function.每次调用函数时都会重新计算该值。

This function only includes canonical zone names and does not include “special” zones such as those under the posix/ and right/ directories, or the posixrules zone.此函数仅包括规范区域名称,不包括“特殊”区域,如posix/right/目录下的区域,或posixrules区域。

Caution小心

This function may open a large number of files, as the best way to determine if a file on the time zone path is a valid time zone is to read the “magic string” at the beginning.此函数可以打开大量文件,因为确定时区路径上的文件是否为有效时区的最佳方法是读取开头的“魔术字符串”。

Note

These values are not designed to be exposed to end-users; for user facing elements, applications should use something like CLDR (the Unicode Common Locale Data Repository) to get more user-friendly strings. See also the cautionary note on ZoneInfo.key.这些值的设计目的不是向最终用户公开;对于面向用户的元素,应用程序应该使用类似CLDR(Unicode公共区域设置数据存储库)的东西来获得更用户友好的字符串。另请参阅ZoneInfo.key键上的注意事项。

zoneinfo.reset_tzpath(to=None)

Sets or resets the time zone search path (TZPATH) for the module. 设置或重置模块的时区搜索路径(TZPATH)。When called with no arguments, TZPATH is set to the default value.在没有参数的情况下调用时,TZPATH设置为默认值。

Calling reset_tzpath will not invalidate the ZoneInfo cache, and so calls to the primary ZoneInfo constructor will only use the new TZPATH in the case of a cache miss.调用reset_tzpath不会使ZoneInfo缓存无效,因此对主ZoneInfo构造函数的调用将仅在缓存未命中的情况下使用新的TZPATH

The to parameter must be a sequence of strings or os.PathLike and not a string, all of which must be absolute paths. to参数必须是字符串或类似os.PathLike序列,而不是字符串,所有这些都必须是绝对路径。ValueError will be raised if something other than an absolute path is passed.如果传递的不是绝对路径,则将引发。

Globals全局

zoneinfo.TZPATH

A read-only sequence representing the time zone search path – when constructing a ZoneInfo from a key, the key is joined to each entry in the TZPATH, and the first file found is used.表示时区搜索路径的只读序列-当从键构造ZoneInfo时,键连接到TZPATH中的每个条目,并使用找到的第一个文件。

TZPATH may contain only absolute paths, never relative paths, regardless of how it is configured.TZPATH只能包含绝对路径,而不能包含相对路径,无论其配置如何。

The object that zoneinfo.TZPATH points to may change in response to a call to reset_tzpath(), so it is recommended to use zoneinfo.TZPATH rather than importing TZPATH from zoneinfo or assigning a long-lived variable to zoneinfo.TZPATH.zoneinfo.TZPATH指向的对象可能会随着reset_tzpath()的调用而更改,因此建议使用zoneinfo.TZPATH,而不是从zoneinfo导入TZPATH或将长寿命变量分配给zoneinfo.TZPATH

For more information on configuring the time zone search path, see Configuring the data sources.有关配置时区搜索路径的更多信息,请参阅配置数据源

Exceptions and warnings例外和警告

exceptionzoneinfo.ZoneInfoNotFoundError

Raised when construction of a ZoneInfo object fails because the specified key could not be found on the system. 由于在系统上找不到指定的键,ZoneInfo对象的构造失败时引发。This is a subclass of KeyError.这是KeyError的一个子类。

exceptionzoneinfo.InvalidTZPathWarning

Raised when PYTHONTZPATH contains an invalid component that will be filtered out, such as a relative path.PYTHONTZPATH包含将被筛选出的无效组件(例如相对路径)时引发。