官方鏈接: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過渡模糊期間使用,以解決模糊。