zoneinfo
— IANA 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另请参见
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
:ZoneInfo
是datetime.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 这些时区还支持PEP 495中引入的fold
attribute introduced in 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 如果系统数据和tzdata都不可用,则对ZoneInfo
will raise ZoneInfoNotFoundError
.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:可以通过三种方式配置此行为:
The default如果未另行指定,则可以在编译时配置默认TZPATH
when not otherwise specified can be configured at compile time.TZPATH
。可以使用环境变量配置TZPATH
can be configured using an environment variable.TZPATH
。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 在POSIX系统上,下游分发服务器和那些从源代码构建Python并知道其系统时区数据部署在何处的分发服务器可以通过指定编译时选项TZPATH
(or, more likely, the configure flag --with-tzpath
), which should be a string delimited by os.pathsep
.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 raiseInvalidTZPathWarning
, 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 要将系统设置为忽略系统数据并改用tzdata包,请设置PYTHONTZPATH=""
.PYTHONTZPATH=""
。
Runtime configuration运行时配置¶
The TZ search path can also be configured at runtime using the TZ搜索路径也可以在运行时使用reset_tzpath()
function. 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
类¶
ZoneInfo
class-
class
zoneinfo.
ZoneInfo
(key)¶ A concrete一个具体的datetime.tzinfo
subclass that represents an IANA time zone specified by the stringkey
.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 ofkey
, the following assertion will always be true:ZoneInfo.clear_cache()
使缓存无效,否则对于key
的所有值,以下断言始终为真:a = ZoneInfo(key)
b = ZoneInfo(key)
assert a is bkey
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 raiseZoneInfoNotFoundError
.key
,构造函数将引发ZoneInfoNotFoundError
。
The ZoneInfo
class has two alternate constructors:ZoneInfo
类有两个备用构造函数:
-
classmethod
ZoneInfo.
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 anio.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)。
-
classmethod
ZoneInfo.
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:以下类方法也可用:
-
classmethod
ZoneInfo.
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
orAsia/Tokyo
).key
的值,该值应该是IANA时区数据库(例如,America/New_York
、Europe/Paris
或Asia/Tokyo
)中的查找键。For zones constructed from file without specifying a对于从文件构造的分区,如果未指定key
parameter, this will be set toNone
.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.ZoneInfo
的repr
是实现定义的,在不同版本之间不一定稳定,但保证不是有效的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
文件的行为取决于其构造方式:
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 fromZoneInfo("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
TrueZoneInfo.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 fromZoneInfo.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
FalseZoneInfo.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如果最终用户希望pickle从文件构造的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.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/
andright/
directories, or theposixrules
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这些值的设计目的不是向最终用户公开;对于面向用户的元素,应用程序应该使用类似CLDR(Unicode公共区域设置数据存储库)的东西来获得更用户友好的字符串。另请参阅ZoneInfo.key
.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 theZoneInfo
cache, and so calls to the primaryZoneInfo
constructor will only use the newTZPATH
in the case of a cache miss.reset_tzpath
不会使ZoneInfo
缓存无效,因此对主ZoneInfo
构造函数的调用将仅在缓存未命中的情况下使用新的TZPATH
。Theto
parameter must be a sequence of strings oros.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 theTZPATH
, 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 thatzoneinfo.TZPATH
points to may change in response to a call toreset_tzpath()
, so it is recommended to usezoneinfo.TZPATH
rather than importingTZPATH
fromzoneinfo
or assigning a long-lived variable tozoneinfo.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例外和警告¶
-
exception
zoneinfo.
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
的一个子类。
-
exception
zoneinfo.
InvalidTZPathWarning
¶ Raised when当PYTHONTZPATH
contains an invalid component that will be filtered out, such as a relative path.PYTHONTZPATH
包含将被筛选出的无效组件(例如相对路径)时引发。