问题描述
考虑以下几点:
from datetime import datetime
import pytz
new_years_in_new_york = datetime(
year=2020,
month=1,
day=1,
hour=0,
minute=0,
tzinfo = pytz.timezone('US/Eastern'))
我现在有一个日期时间对象,它代表纽约的 1 月 1 日午夜.奇怪的是,如果我使用 pytz 将其转换为 UTC,我会得到一个奇怪的 datetime 几分钟:
I now I have a datetime object representing January 1, midnight, in New York. Oddly, if I use pytz to convert this to UTC, I'll get an odd datetime off by several minutes:
new_years_in_new_york.astimezone(pytz.utc)
# datetime.datetime(2020, 1, 1, 4, 56, tzinfo=<UTC>)
请注意,纽约的 pytz 午夜是世界协调时 4:56.在 Stack Overflow 的其他地方,我了解到这是因为 pytz 使用您的 /usr/share/zoneinfo
数据,它在标准化之前使用当地平均时间来说明时区.这可以在这里显示:
Notice that midnight in New York, in pytz, is 4:56 in UTC. Elsewhere on Stack Overflow, I learned that's because pytz uses your /usr/share/zoneinfo
data, which uses local mean time to account for timezones before standardization. This can be shown here:
pytz.timezone('US/Eastern')
# <DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>
看到那个LMK-1 day, 19:04:00 STD
了吗?这是当地的平均时间偏移量,而不是我想要的偏移量,在夏令时是美国/东部不是.
See that LMK-1 day, 19:04:00 STD
? That's a local mean time offset, not the offset I want, which is US/Eastern not during daylight savings time.
有没有一种方法可以强制 pytz 使用基于当前日期的当前标准偏移量集?在 2020 年新年,它应该只是 UTC-5.如果我提供的日期是在夏令时,我会想要 UTC-4.我很困惑为什么 pytz 会在 2020 日期使用基于 LMT 的偏移量.
Is there a way I can force pytz to use what is currently the standard set of offsets based on a current date? On New Years 2020, it should just be UTC-5. If the date I supplied were during daylight savings time, I would want UTC-4. I'm confused as to why pytz would use a LMT-based offset for a 2020 date.
推荐答案
>>> new_years_in_new_york
datetime.datetime(2020, 1, 1, 0, 0, tzinfo=<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>)
注意那个日期时间的奇数偏移.您没有正确创建此日期时间.
Notice the odd offset in that datetime. You're not creating this datetime correctly.
该库仅支持两种构建本地化时间的方法.这首先是使用pytz库提供的localize()
方法.这用于本地化一个天真的日期时间(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'
不幸的是使用标准 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'
http://pytz.sourceforge.net/#localized-times-and-date-arithmetic
这篇关于如何强制 pytz 使用当前的标准时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!