我面临 python 时区问题,并且不确定处理它的正确方法是什么。我必须根据给定的开始和结束 DateTime 对象计算时间增量。在我的活动进行期间,夏令时可能会发生变化,所以我必须考虑到这一点。
到目前为止,我已经了解到,要实现此目的,我需要将开始和结束时间保存为时区感知的 DateTime 对象,而不是常规的 UTC DateTimes。
我一直在研究 DateTime.tzinfo、pytz 和 dateutil,但据我了解,这些都主要集中在 UTC DateTime 对象的本地化显示或计算不同时区之间的偏移量。我发现其他助手期望时区作为 UTC 偏移量,因此已经要求我知道日期是否受到夏令时的影响。
所以,我想我的问题是:有没有办法将日期时间保存为“中欧”,并在使用它们进行计算时了解白天的节省?或者,如果不是,检查两个 DateTime 对象是否在夏令时内的既定方法是什么,以便我可以在必要时手动调整结果?
如有任何指点,我将不胜感激。
您只需要生成一个感知(本地化)
datetime
实例,然后您用它进行的任何计算都会考虑夏令时。这里以pytz
为例:
>>> import pytz
>>> from datetime import *
>>> berlin = pytz.timezone('Europe/Berlin')
>>> d1 = berlin.localize(datetime(2023, 3, 25, 12))
datetime.datetime(2023, 3, 25, 12, 0, tzinfo=<DstTzInfo 'Europe/Berlin' CET+1:00:00 STD>)
>>> d2 = berlin.localize(datetime(2023, 3, 26, 12))
datetime.datetime(2023, 3, 26, 12, 0, tzinfo=<DstTzInfo 'Europe/Berlin' CEST+2:00:00 DST>)
>>> d2 - d1
datetime.timedelta(seconds=82800)
>>> (d2 - d1).total_seconds() / 60 / 60
23.0