给出一个包含巴黎时区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()意外结果
发布评论