使用DST小时发现timedelta差异(Python) [英] Find timedelta difference with DST hours (Python)
问题描述
鉴于两个日期时间,例如2020-01-01 00:00:00和2020-04-01 00:00:00,我想获得两个日期之间的时间差,以小时数为单位,由于夏令时而造成的任何加法/减法。我不确定如何继续。
Given two datetimes such as 2020-01-01 00:00:00 and 2020-04-01 00:00:00, I want to get the timedelta between the two dates in terms of number of hours with any addition/subtraction due to daylight saving time. I am not sure how I can proceed.
推荐答案
默认情况下,timedelta是时间差,而不是太阳能时间。以获得 DST意识 timedelta,您需要将datetime对象本地化到某个时区(具有DST),并考虑两个datetime对象的UTC偏移量。例如。就像
by default, timedelta is difference in time, not "solar time". to get a "DST aware" timedelta, you will need to localize the datetime objects to a certain time zone (that has the DST) and take into account the UTC offset of the two datetime objects. E.g. like
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
这篇关于使用DST小时发现timedelta差异(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!