我正在使用strptime创建一个日期时间对象,设置为“2016-01-02 03:04:05”,时区为“Europe / Madrid”。然后我将其转换为UTC。
为什么它会增加15分钟而不是减去1小时?
如果我使用"CET"而不是"Europe/Madrid",它会正常工作:
为什么它会增加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:也许这是一个“使用标准datetime构造函数的tzinfo参数”与pytz在许多时区上“不起作用”的实例?来源