gpt4 book ai didi

Python astimezone() 意外结果

转载 作者:行者123 更新时间:2023-12-01 01:38:54 29 4
gpt4 key购买 nike

给定一个变量,其中包含巴黎时区 2000-01-01 00:01 的日期时间(据我所知,冬季为 UTC+2):

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

我预计转换为 UTC 会得到 1999-12-31 22:01 的日期时间,但结果却是:

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

我错过了什么?

谢谢

最佳答案

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'

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”…?!这是历史偏移,而不是当前标准。

datetime 无法正确处理 pytz 返回的时区包(包含自永远以来的所有历史偏移量),并且它选择了一些随机值(嗯,第一个可能)偏移量而不是与实际时间相关的偏移量。可以说,由于它需要首先正确解释时间,因此它无法从时区包中选择正确的时间偏移量。

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

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() 意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52116495/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com