Python astimezone()意外结果

编程入门 行业动态 更新时间:2024-10-26 11:26:41
本文介绍了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'

pytz.sourceforge

更多推荐

Python astimezone()意外结果

本文发布于:2023-11-13 14:14:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584539.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:意外   Python   astimezone

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!