【发布时间】:2016-06-08 11:30:56
【问题描述】:
我正在通过 strptime 创建一个日期时间对象,通过 pytz 在“欧洲/马德里”时区设置为“2016-01-02 03:04:05”。然后我将其转换为 UTC。
为什么要加 15 分钟而不是减 1 小时?
>>> import datetime
>>> import pytz
>>> d = datetime.datetime.strptime('2016-01-02 03:04:05', '%Y-%m-%d %H:%M:%S')
>>> d
datetime.datetime(2016, 1, 2, 3, 4, 5)
>>> d = d.replace(tzinfo=pytz.timezone('Europe/Madrid'))
>>> d
datetime.datetime(2016, 1, 2, 3, 4, 5, tzinfo=<DstTzInfo 'Europe/Madrid' LMT-1 day, 23:45:00 STD>)
>>> d.astimezone(pytz.utc)
datetime.datetime(2016, 1, 2, 3, 19, 5, tzinfo=<UTC>)
如果我使用“CET”而不是“Europe/Madrid”,它可以正常工作:
>>> d = d.replace(tzinfo=pytz.timezone('CET'))
>>> d
datetime.datetime(2016, 1, 2, 3, 4, 5, tzinfo=<DstTzInfo 'CET' CET+1:00:00 STD>)
>>> d.astimezone(pytz.utc)
datetime.datetime(2016, 1, 2, 2, 4, 5, tzinfo=<UTC>)
编辑 1:Python 版本为 2.7.11。 pytz版本是2015.7。
编辑 2:可能的解决方案是使用 d = pytz.timezone('Europe/Madrid').localize(d) 而不是 d = d.replace(tzinfo=pytz.timezone('Europe/Madrid')):
>>> d = datetime.datetime.strptime('2016-01-02 03:04:05', '%Y-%m-%d %H:%M:%S')
>>> d
datetime.datetime(2016, 1, 2, 3, 4, 5)
>>> d = pytz.timezone('Europe/Madrid').localize(d)
>>> d
datetime.datetime(2016, 1, 2, 3, 4, 5, tzinfo=<DstTzInfo 'Europe/Madrid' CET+1:00:00 STD>)
>>> d.astimezone(pytz.utc)
datetime.datetime(2016, 1, 2, 2, 4, 5, tzinfo=<UTC>)
编辑 3:也许这是“在许多时区使用标准日期时间构造函数的 tzinfo 参数对 pytz '不起作用'”的一个实例? Source
【问题讨论】: