Python astimezone()意外结果 [英] Python astimezone() unexpected result

查看:170
本文介绍了Python astimezone()意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个包含巴黎时区2000-01-01 00:01日期时间的变量(冬季afaik中为UTC + 2):

Given a variable containing the datetime of 2000-01-01 00:01 in Paris timezone (UTC+2 in winter afaik):

datetime.datetime(2000, 1, 1, 0, 1, tzinfo=pytz.timezone('Europe/Paris'))

我希望转换为UTC会导致日期时间为1999-12-31 22:01,但改为:

I expected the conversion to UTC to result in a datetime of 1999-12-31 22:01, but got instead:

datetime.datetime(2000, 1, 1, 0, 1, tzinfo=pytz.timezone('Europe/Paris')).astimezone(pytz.utc)
datetime.datetime(1999, 12, 31, 23, 52, tzinfo=<UTC>)

我是什么缺少吗?

谢谢

推荐答案


不幸的是,使用标准 datetime
构造函数的 tzinfo 参数,对于 pytz 用于许多时区。

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

>>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=amsterdam).strftime(fmt)
'2002-10-27 12:00:00 LMT+0020'

对于没有夏令时的时区来说是安全的,例如UTC:

It is safe for timezones without daylight saving transitions though, such as UTC:

>>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=pytz.utc).strftime(fmt)
'2002-10-27 12:00:00 UTC+0000'


您会注意到:

>>> datetime.datetime(2000, 1, 1, 0, 1, tzinfo=pytz.timezone('Europe/Paris'))
datetime.datetime(2000, 1, 1, 0, 1, tzinfo=<DstTzInfo 'Europe/Paris' LMT+0:09:00 STD>)

LMT + 0:09 :00 STD…?!这是历史偏移量,不是当前标准。

"LMT+0:09:00 STD"…?! That's a historical offset, not a current standard.

pytz datetime 之前未正确处理,它选择了一些随机的偏移量(好吧,可能是 first )而不是与实际时间。可以说,由于它首先需要正确地解释时间,因此不能从时区捆绑中选择正确的时间偏移。

The timezone bundles (containing all historical offsets since forever) returned by pytz aren't handled correctly by datetime, and it chooses some random (well, the first probably) offset instead of the offset pertinent to the actual time. Arguably, since it needs to interpret the time correctly first it cannot choose the right offset by time from the timezone bundle.


此库仅支持建立本地化时间的两种方式。
首先是使用 pytz 库提供的 localize()方法。
这用于本地化 datetime datetime 没有时区
信息)的本地化:

This library only supports two ways of building a localized time. The first is to use the localize() method provided by the pytz library. This is used to localize a naive datetime (datetime with no timezone information):

>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0))
>>> print(loc_dt.strftime(fmt))
2002-10-27 06:00:00 EST-0500 

构建本地化时间的第二种方法是通过使用标准 astimezone()方法转换现有的
本地化时间:

The second way of building a localized time is by converting an existing localized time using the standard astimezone() method:

>>> ams_dt = loc_dt.astimezone(amsterdam)
>>> ams_dt.strftime(fmt)
'2002-10-27 12:00:00 CET+0100'

http://pytz.sourceforge.net

这篇关于Python astimezone()意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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