官方链接:https://pypi.org/project/pytz/
Introduction
pytz brings the Olson tz database into Python. This library allows accurate and cross platform timezone calculations using Python 2.4 or higher. It also solves the issue of ambiguous times at the end of daylight saving time, which you can read more about in the Python Library Reference (datetime.tzinfo).
pytz将Olson-tz数据库引入Python。这个库允许使用python2.4或更高版本进行精确的跨平台时区计算。它还解决了夏令时结束时时间不明确的问题,您可以在Python库参考中了解更多(datetime.tzinfo).
Almost all of the Olson timezones are supported.
几乎所有的Olson时区都支持。
Note
This library differs from the documented Python API for tzinfo implementations; if you want to create local wallclock times you need to use the localize() method documented in this document. In addition, if you perform date arithmetic on local times that cross DST boundaries, the result may be in an incorrect timezone (ie. subtract 1 minute from 2002-10-27 1:00 EST and you get 2002-10-27 0:59 EST instead of the correct 2002-10-27 1:59 EDT). A normalize() method is provided to correct this. Unfortunately these issues cannot be resolved without modifying the Python datetime implementation (see PEP-431).
此库与用于tzinfo实现的文档化Python API不同;如果要创建本地wallcock时间,则需要使用本文中介绍的localize()方法。此外,如果您在跨越DST边界的本地时间上执行日期运算,结果可能位于错误的时区(即从2002-10-27 1:00 EST减去1分钟,您得到的是2002-10-27 0:59 EST,而不是正确的2002-10-27 1:59 EDT)。提供了normalize()方法来纠正这种情况。不幸的是,如果不修改Python日期时间实现(参见PEP-431),就无法解决这些问题。
Installation
This package can either be installed using pip or from a tarball using the standard Python distutils.
这个包可以使用pip安装,也可以使用标准Python distutils从一个压缩包安装。
If you are installing using pip, you don’t need to download anything as the latest version will be downloaded for you from PyPI:
如果您使用pip安装,则不需要下载任何内容,因为最新版本将从PyPI下载:
pip install pytz
If you are installing from a tarball, run the following command as an administrative user:
如果您从一个tarball安装,请使用管理用户运行以下命令:
python setup.py install
pytz for Enterprise
pytz商用
Available as part of the Tidelift Subscription.
The maintainers of pytz and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use.
Example & Usage
例子和使用
Localized times and date arithmetic
局部时间和日期算法
In [1]: from datetime import datetime, timedelta In [2]: from pytz import timezone In [3]: import pytz In [4]: utc = pytz.utc In [5]: utc.zone Out[5]: 'UTC' In [6]: eastern = timezone('US/Eastern') In [7]: eastern.zone Out[7]: 'US/Eastern' In [8]: amsterdam = timezone('Europe/Amsterdam') In [9]: fmt = '%Y-%m-%d %H:%M:%S %Z%z'
This library only supports two ways of building a localized time. The first is to use the localize() method provided by the pytz library. This is used to localize a naive datetime (datetime with no timezone information):
这个库只支持两种构建本地化时间的方法。第一种方法是使用pytz库提供的localize()方法。这是用来本地化一个简单的日期时间(没有时区信息的日期时间):
In [16]: loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0)) In [17]: loc_dt.strftime(fmt) Out[17]: '2002-10-27 06:00:00 EST-0500' In [18]: loc_dt Out[18]: datetime.datetime(2002, 10, 27, 6, 0, tzinfo=<DstTzInfo 'US/Eastern' EST-1 day, 19:00:00 STD>) In [19]:
The second way of building a localized time is by converting an existing localized time using the standard astimezone() method:
构建本地化时间的第二种方法是使用标准的astimezone()方法转换现有的本地化时间:
In [19]: ams_dt = loc_dt.astimezone(amsterdam) In [20]: ams_dt.strftime(fmt) Out[20]: '2002-10-27 12:00:00 CET+0100'
amsterdam为东1区,美东时间为东5区
Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones.
不幸的是,对于许多时区,使用标准datetime构造函数的tzinfo参数在pytz中“不起作用”。
In [21]: datetime(2002, 10, 27, 12, 0, 0, tzinfo=amsterdam).strftime(fmt) Out[21]: '2002-10-27 12:00:00 LMT+0020'
It is safe for timezones without daylight saving transitions though, such as UTC:
对于没有夏令时转换的时区是安全的,比如UTC:
In [22]: datetime(2002, 10, 27, 12, 0, 0, tzinfo=pytz.utc).strftime(fmt) Out[22]: '2002-10-27 12:00:00 UTC+0000'
The preferred way of dealing with times is to always work in UTC, converting to localtime only when generating output to be read by humans.
处理时间的首选方法是始终使用UTC,只有在生成供人类读取的输出时才转换为本地时间。
In [36]: utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc) In [37]: loc_dt = utc_dt.astimezone(eastern) In [38]: loc_dt.strftime(fmt) Out[38]: '2002-10-27 01:00:00 EST-0500'
This library also allows you to do date arithmetic using local times, although it is more complicated than working in UTC as you need to use the normalize() method to handle daylight saving time and other timezone transitions. In this example, loc_dt is set to the instant when daylight saving time ends in the US/Eastern timezone.
这个库还允许使用本地时间进行日期计算,尽管它比使用UTC更复杂,因为您需要使用normalize()方法来处理日光节约时间和其他时区转换。在本例中,loc_dt被设置为夏令时在美国/东部时区结束时的瞬间。
In [56]: utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc) In [57]: loc_dt = utc_dt.astimezone(eastern) In [58]: before = loc_dt-timedelta(minutes=10) In [60]: before.strftime(fmt) Out[60]: '2002-10-27 00:50:00 EST-0500' In [61]: eastern.normalize(before).strftime(fmt) Out[61]: '2002-10-27 01:50:00 EDT-0400' In [62]: after = eastern.normalize(before + timedelta(minutes=20)) In [63]: after.strftime(fmt) Out[63]: '2002-10-27 01:10:00 EST-0500' # 相同的,于上面 In [64]: eastern.normalize(after).strftime(fmt) Out[64]: '2002-10-27 01:10:00 EST-0500' In [65]:
在处理时区问题时候,由于27日1时是冬令至的时间,这个时间其实是夏令至的事前往前调整的一个小时,也就是调慢了一个小时。所以在冬令至节点往前的时间应该为夏令至的时间。
Creating local times is also tricky, and the reason why working with local times is not recommended. Unfortunately, you cannot just pass a tzinfo argument when constructing a datetime (see the next section for more details)
创建本地时间也很棘手,这也是不推荐使用本地时间的原因。不幸的是,在构造datetime时不能只传递tzinfo参数(更多细节请参阅下一节)
In [68]: dtt = datetime(2002, 10, 22, 1, 30, 0) In [69]: dt1 = eastern.localize(dtt, is_dst=True) In [70]: dt1.strftime(fmt) Out[70]: '2002-10-22 01:30:00 EDT-0400' In [71]: dt3 = eastern.localize(dtt) In [72]: dt3 Out[72]: datetime.datetime(2002, 10, 22, 1, 30, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>) In [73]: dt3.strftime(fmt) Out[73]: '2002-10-22 01:30:00 EDT-0400' In [74]: eastern.localize(datetime(2002, 10, 30, 1, 30, 0)).strftime(fmt) Out[74]: '2002-10-30 01:30:00 EST-0500' In [75]: eastern.localize(datetime(2002, 10, 30, 1, 30, 0)) Out[75]: datetime.datetime(2002, 10, 30, 1, 30, tzinfo=<DstTzInfo 'US/Eastern' EST-1 day, 19:00:00 STD>) In [76]: dt Out[76]: datetime.datetime(2002, 10, 27, 1, 30) In [77]: dt4 = eastern.localize(dt, is_dst=True) In [78]: dt4.strftime(fmt) Out[78]: '2002-10-27 01:30:00 EDT-0400' In [80]: dt4 = eastern.localize(dt, is_dst=False) In [81]: dt4.strftime(fmt) Out[81]: '2002-10-27 01:30:00 EST-0500' In [82]:
在使用localize的方法,可以通过is_dst来强制设置是否为夏令时,夏令时的格式化输出为EDT,非夏令时的格式化输出为EST
Converting between timezones is more easily done, using the standard astimezone method.
使用标准的astimezone方法,时区之间的转换更容易完成。
In [99]: utc_dt = utc.localize(datetime.utcfromtimestamp(1143408899)) In [100]: utc_dt.strftime(fmt) Out[100]: '2006-03-26 21:34:59 UTC+0000' In [101]: au_tz = timezone('Australia/Sydney') In [102]: au_dt = utc_dt.astimezone(au_tz) In [103]: au_dt.strftime(fmt) Out[103]: '2006-03-27 08:34:59 AEDT+1100' In [104]: utc_dt2 = au_dt.astimezone(utc) In [106]: utc Out[106]: <UTC> In [107]: utc_dt2.strftime(fmt) Out[107]: '2006-03-26 21:34:59 UTC+0000' In [108]: utc_dt == utc_dt2 Out[108]: True In [109]:
You can take shortcuts when dealing with the UTC side of timezone conversions. normalize() and localize() are not really necessary when there are no daylight saving time transitions to deal with.
在处理时区转换的UTC端时,可以采用一些快捷方式。当不需要处理夏时制时间转换时,normalize()和localize()实际上是不必要的。
In [115]: utc_dt = datetime.utcfromtimestamp(1143408899).replace(tzinfo=utc) In [116]: utc_dt.strftime(fmt) Out[116]: '2006-03-26 21:34:59 UTC+0000' In [117]: au_tz = timezone('Australia/Sydney')
# 0时区时间对象转换成au_tz时区时间对象,通过normalize处置夏令逻辑 In [118]: au_dt = au_tz.normalize(utc_dt.astimezone(au_tz)) In [119]: au_dt.strftime(fmt) Out[119]: '2006-03-27 08:34:59 AEDT+1100' In [120]: utc_dt2 = au_dt.astimezone(utc) In [121]: utc_dt2.strftime(fmt) Out[121]: '2006-03-26 21:34:59 UTC+0000' In [122]: utc_dt == utc_dt2 Out[122]: True In [123]:
tzinfo API
The tzinfo instances returned by the timezone() function have been extended to cope with ambiguous times by adding an is_dst parameter to the utcoffset(), dst() && tzname() methods.
通过向utcoffset()、dst() && tzname()方法添加is_dst参数,timezone()函数返回的tzinfo实例已经被扩展,以应对时间不明确的情况。
tz = timezone('America/St_Johns')
In [126]: normal = datetime(2009, 9, 1) In [127]: ambiguous = datetime(2009, 10, 31, 23, 30)
The is_dst parameter is ignored for most timestamps. It is only used during DST transition ambiguous periods to resolve that ambiguity.
对于大多数时间戳,is_dst参数被忽略。它只在DST过渡模糊期间使用,以解决模糊。