from zoneinfo import ZoneInfo
import datetime
dt = datetime.datetime(2038,3,14,0,0, tzinfo = ZoneInfo(r'America/New_York'))
print(dt) # Output: 2038-03-14 00:00:00-05:00
dt2 = datetime.datetime(2038,3,14,3,0, tzinfo = ZoneInfo(r'America/New_York'))
print(dt2) # Output: 2038-03-14 03:00:00-04:00
timedelta = dt2-dt1
print(timedelta) # Output: 3:00:00
以上是正确的,因为它知道 DST,也就是在 DST 感知上下文中。例如,如果您像下面的代码一样将 3 小时添加到 2038-03-14 00:00:00-05:00,您会得到一致的结果:
from zoneinfo import ZoneInfo
import datetime
dt = datetime.datetime(2038,3,14,0,0, tzinfo = ZoneInfo(r'America/New_York'))
print(dt) # Output: 2038-03-14 00:00:00-05:00
print(dt+datetime.timedelta(hours=3)) # Output: 2038-03-14 03:00:00-04:00
但是,在 NO-DST-AWARE 上下文中,您对 2 小时时差的想法是正确的,如下所示:
from zoneinfo import ZoneInfo
import datetime
dt = datetime.datetime(2038,3,14,0,0, tzinfo = ZoneInfo(r'America/New_York'))
print(dt) # Output: 2038-03-14 00:00:00-05:00
dt2 = datetime.datetime(2038,3,14,3,0, tzinfo = ZoneInfo(r'America/New_York'))
print(dt2) # Output: 2038-03-14 03:00:00-04:00
dt_isoformat = dt.isoformat()
print(dt_isoformat) # Output: 2038-03-14T00:00:00-05:00
dt2_isoformat = dt2.isoformat()
print(dt2_isoformat) # Output: 2038-03-14T03:00:00-04:00
print(datetime.datetime.fromisoformat(dt2_isoformat)-datetime.datetime.fromisoformat(dt_isoformat)) # Output: 2:00:00