本文介绍了如何强制pytz使用当前的标准时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容:

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,我将得到几分钟的奇异日期时间:

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表示的时间是UTC的 4:56 。在堆栈溢出的其他地方,我了解到这是因为数据,该数据使用本地平均时间来说明标准化之前的时区。可以在此处显示:

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天,标准时间19:04:00 ?那是本地平均时间偏移,不是我想要的偏移,这是夏令时期间的美国/东部 not

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.

>>> 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 anexisting 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 datetimeconstructors ‘’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'

这篇关于如何强制pytz使用当前的标准时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 16:03