【发布时间】:2020-12-14 04:49:27
【问题描述】:
给定两个日期时间,例如 2020-01-01 00:00:00 和 2020-04-01 00:00:00,我想获得两个日期之间的时间增量(以小时数表示)由于夏令时而进行的任何加法/减法。我不确定如何继续。
【问题讨论】:
给定两个日期时间,例如 2020-01-01 00:00:00 和 2020-04-01 00:00:00,我想获得两个日期之间的时间增量(以小时数表示)由于夏令时而进行的任何加法/减法。我不确定如何继续。
【问题讨论】:
默认情况下,Python 的 timedelta 会为您提供已知日期时间对象(附加时区的对象)的时间差 - 而不是绝对时间(在物理意义上;第二个为 SI unit)。
要获得“DST 感知”时间增量,首先确保日期时间对象本地化到某个时区(具有 DST)。然后,考虑两个日期时间对象的 UTC 偏移量;比如喜欢
from datetime import datetime
from dateutil.tz import gettz
t0, t1 = "2020-03-07 00:00:00", "2020-03-09 00:00:00"
# to datetime object
t0, t1 = datetime.fromisoformat(t0), datetime.fromisoformat(t1)
# set appropriate timezone
tzone = gettz("US/Eastern")
t0, t1 = t0.replace(tzinfo=tzone), t1.replace(tzinfo=tzone)
# check if UTC offset changed
utcdelta = t1.utcoffset() - t0.utcoffset()
# now calculate the timedelta
td = t1 - t0 - utcdelta
print(td)
# 1 day, 23:00:00
为了进一步阅读,我推荐 Paul Ganssle 的 Semantics of timezone-aware datetime arithmetic 博客文章。
【讨论】: