[英]Python datetime + pytz issue
I'm creating a datetime object via strptime, set to "2016-01-02 03:04:05" in the "Europe/Madrid" timezone via pytz. 我正在通过strptime创建一个日期时间对象,通过pytz在“Europe / Madrid”时区设置为“2016-01-02 03:04:05”。 Then I'm converting it to UTC.
然后我将它转换为UTC。
Why does it add 15 minutes instead of subtract 1 hour? 为什么它增加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>)
It works correctly if instead of using "Europe/Madrid" I use "CET": 如果不使用“Europe / Madrid”我使用“CET”,它可以正常工作:
>>> 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>)
Edit 1: Python version is 2.7.11. 编辑1:Python版本是2.7.11。 pytz version is 2015.7.
pytz版本是2015.7。
Edit 2: Possible solution is to use d = pytz.timezone('Europe/Madrid').localize(d)
instead of d = d.replace(tzinfo=pytz.timezone('Europe/Madrid'))
: 编辑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>)
Edit 3: Perhaps this is an instance of "using the tzinfo argument of the standard datetime constructors 'does not work' with pytz for many timezones"? 编辑3:也许这是一个“使用标准日期时间构造函数的tzinfo参数'的实例不适用于许多时区的pytz”? Source
资源
Yes, the problem is in 是的,问题在于
d.replace(tzinfo=pytz.timezone('Europe/Madrid'))
where it applies the first known UTC offset in Madrid (called LMT = Local Mean Time), which was 15 minutes behind UTC (valid until 1900), or in this case expressed as -1 day +23:45
: 它应用了马德里第一个已知的UTC偏移(称为LMT =本地平均时间),比UTC晚了15分钟(有效期至1900年),或者在这种情况下表示为
-1 day +23:45
:
datetime.datetime(2016, 1, 2, 3, 4, 5, tzinfo=<DstTzInfo 'Europe/Madrid' LMT-1 day, 23:45:00 STD>)
Use 采用
pytz.timezone('Europe/Madrid').localize(d)
instead: 代替:
datetime.datetime(2016, 1, 2, 3, 4, 5, tzinfo=<DstTzInfo 'Europe/Madrid' CET+1:00:00 STD>)
which will apply the UTC offset valid in 2016, ie CE(S)T. 这将应用2016年有效的UTC偏移,即CE(S)T。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.