如何获取 Python 中任何时区的当前偏移量

How to get current offset of any timezone in Python

我需要获取 Python 中任何时区的当前偏移量。目前我正在使用 pytz 库,我正在使用以下代码获取偏移量:

import datetime
import pytz
timezone = 'America/Punta_Arenas'
datetime.datetime.now(pytz.timezone(timezone)).utcoffset().total_seconds()/60/60
//prints -3
timezone = 'America/Santiago'
datetime.datetime.now(pytz.timezone(timezone)).utcoffset().total_seconds()/60/60
//prints -4

举个例子'America/Santiago':今年(2018年)夏令时定在5月13日,而2015年全年都是夏令时,2014年定为4月27日。因此,以日期和年份为准,偏移量为“-3”或“-4”。

我假设之前的代码不知道每个国家/地区关于 DST 的政治决定,并且可能根据固定的 DST 日期或类似的东西让您获得偏移量。由于我不知道 datetimepytz 的具体细节,所以我想问一下,这个假设是否正确?

如果不知道,我怎样才能获得任何时区的实际当前偏移量?

I assume the previous code is not aware of the political decisions of each country regarding DST and probably gets you the offset according to fixed DST dates or something like that.

您的假设不正确。时区的政治变化通过 TZ Database 记录和分发。然后,这些更改会在数百个不同的库、平台和操作系统中实现——例如您提到的 pytz 库。

您描述的 America/Santiago 的变化反映在 TZDB 2016c, which is implemented in pytz 2016.3 中。如果您使用的是 pytz 2016.3 或更高版本,那么您的代码会知道此更改。

Pytz 很好,但您可能要考虑使用 dateutil instead. Version 2.5.2 或更高版本有此数据。