为什么使用来自 pytz 的 tzinfo 创建日期时间会显示奇怪的时间偏移?

Why does creating a datetime with a tzinfo from pytz show a weird time offset?

有人可以解释一下为什么我在那些中没有得到相同的结果吗?

import datetime,pytz
var1 = datetime.datetime(2017,10,25,20,10,50,tzinfo=pytz.timezone("Europe/Athens")))
print(var1)

这段代码的输出是:2017-10-25 20:10:50+01:35

import datetime,pytz
var1 = datetime.datetime(2017,10,25,20,10,50)
var1 = pytz.timezone("Europe/Athens").localize(var1)
print(var1)

这段代码的输出是:2017-10-25 20:10:50+03:00

我的问题是为什么他们有不同的时区(1:35 和3:00)。我知道第二个代码是真的,因为我的 UTC 是 3:00。但是你能告诉我为什么我在第一个中得到 1:35 吗?

在第二个代码中,您使用 .localize(),它接受一个简单的日期时间对象并将其解释为就好像它在该时区中一样。它不会将时间移动到另一个时区。天真的日期时间对象没有时区信息,无法实现该移动。

由于您在第二个代码中设置本地时间,因此第二个代码中显示的时间是正确的。由于您没有在第一个代码中使用本地时间,因此显示的时间不正确。

tzinfo 不适用于某些时区,这可能是导致错误结果的原因。
pytz doc:

Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones.

使用localizeastimezone 可以解决这个问题。 Doc 说 处理时间的首选方法是始终以 UTC 工作,仅在生成可供人类阅读的输出时才转换为本地时间

import datetime, pytz
localTimezone = pytz.timezone('Europe/Athens')
var1 = datetime.datetime(2017,10,25,20,10,50,tzinfo=pytz.utc) 
loc_dt = var1.astimezone(localTimezone)
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
print(loc_dt.strftime(fmt))  

这将打印

2017-10-25 23:10:50 EEST+0300

没问题,datetime 只是愉快地报告 tzinfo 在任何参考系中的偏移量。

默认情况下 pytz.timezone 不提供 UTC 偏移量,但 LMT (local mean time) 偏移量:

>>> pytz.timezone("Europe/Athens")
<DstTzInfo 'Europe/Athens' LMT+1:35:00 STD>
#                          ^^^-------------------- local mean time

然而当你本地化它时:

>>> var1 = datetime.datetime(2017,10,25,20,10,50)
>>> var1 = pytz.timezone("Europe/Athens").localize(var1)
>>> var1.tzinfo
<DstTzInfo 'Europe/Athens' EEST+3:00:00 DST>
#                          ^^^^-------------------- eastern european summer time

现在报告了一个不同的偏移量,这次是基于 EEST。