Python datetime + pytz问题 [英] Python datetime + pytz issue

查看:80
本文介绍了Python datetime + pytz问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过strptime创建一个日期时间对象,并通过pytz在欧洲/马德里时区中将其设置为 2016-01-02 03:04:05。然后将其转换为UTC。

I'm creating a datetime object via strptime, set to "2016-01-02 03:04:05" in the "Europe/Madrid" timezone via pytz. Then I'm converting it to UTC.

为什么要加上15分钟而不是减去1小时?

Why does it add 15 minutes instead of subtract 1 hour?

>>> 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,则它可以正常工作:

It works correctly if instead of using "Europe/Madrid" I use "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>)

编辑1:Python版本为2.7.11。 pytz版本为2015.7。

Edit 1: Python version is 2.7.11. pytz version is 2015.7.

编辑2:可能的解决方案是使用 d = pytz.timezone('Europe / Madrid')。localize(d )而不是 d = d.replace(tzinfo = pytz.timezone('Europe / Madrid'))

Edit 2: Possible solution is to use d = pytz.timezone('Europe/Madrid').localize(d) instead of 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中不起作用'的实例吗?

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"? Source

推荐答案

是的,问题出在

d.replace(tzinfo=pytz.timezone('Europe/Madrid'))

在这里应用马德里的第一个已知UTC偏移量(称为LMT =当地平均时间),该时间为15分钟在UTC后面(有效期至1900年),或在这种情况下表示为 -1天+23:45

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:

datetime.datetime(2016, 1, 2, 3, 4, 5, tzinfo=<DstTzInfo 'Europe/Madrid' LMT-1 day, 23:45:00 STD>)

使用

pytz.timezone('Europe/Madrid').localize(d)

相反: p>

instead:

datetime.datetime(2016, 1, 2, 3, 4, 5, tzinfo=<DstTzInfo 'Europe/Madrid' CET+1:00:00 STD>)

这将应用2016年有效的UTC偏移量,即CE( S)T。

which will apply the UTC offset valid in 2016, i.e. CE(S)T.

这篇关于Python datetime + pytz问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆