Python 时区偏移错误?

Python timezone offset wrong?

我正在编写一个 python 脚本,其中包含两行代码,将传递到方法中的日期转换为 UTC 时间:

print "Timezone: %s" % get_localzone()
date = datetime.now(tz=get_localzone())
print "Local time: %s" % date
utc = pytz.utc
utc_date = date.astimezone(utc)
print "UTC date: %s" % utc_date

结果是:

Timezone: America/Chicago
Local time: 2015-06-17 14:58:45.224827-05:00
UTC date: 2015-06-17 19:58:45.224827+00:00

如您所见,本地时间的偏移量是“-05:00”,这没什么问题,但是当我创建具有相同时区的自定义日期时间对象时:

date = datetime(2015, 6, 17, 14, 58, 45, tzinfo=get_localzone())

结果变为:

Timezone: America/Chicago
Local time: 2015-06-17 14:58:45-05:51

偏移量从“-05:00”更改为“-05:51”。我什至使用了第一个 "datetime.now()" 生成的同一时间,并且时区没有改变,有人可以向我解释为什么会这样吗?谢谢!

不分配 tzinfo 参数,而是使用 pytz 中的 localize 方法。

tz = get_localzone()
date = tz.localize(datetime(2015, 6, 17, 14, 58, 45))

这在 the pytz documentation 中有突出的讨论,从第一个 "Note" 框开始,在第一个代码示例中。

它也在 the tzlocal documentation 中显示,这是(我假设)您的 get_localzone() 方法的来源。

仅供参考,-05:51 偏移量来自原始 LMT value of the America/Chicago time zone, which is -05:50:36 and is assumed to have been in use way back in 1883 as shown here。它四舍五入到最接近的分钟,在 Python 中给出 -05:51 LMT 值。您看到该偏移量是因为未调用 localize 方法,因此 pytz 仅使用该时区条目已知的第一个偏移量。