Home > Blockchain >  Python timedelta spanning DST changeover returns incorrect result?
Python timedelta spanning DST changeover returns incorrect result?

Time:03-15

Daylight Savings time began at 2 AM on March 14th, 2021.

Using Python zoneinfo to create timezone-aware datetimes as follows:

import zoneinfo
from datetime import datetime

tz = zoneinfo.ZoneInfo("US/Eastern")

d0 = datetime(2021, 3, 13, 23, tzinfo=tz)
d1 = datetime(2021, 3, 14, 7, tzinfo=tz)
print(d0, d1, (d1 - d0).total_seconds() / 60 / 60)

I receive output:

2021-03-13 23:00:00-05:00 2021-03-14 07:00:00-04:00 8.0

Python is correctly 'seeing' the UTC offset changeover between these values (-5 vs -4), but why would the resulting time delta equate to 8 instead of 7?

For what it's worth, creating the timezone aware datetimes as follows produces the exact same results:

d0 = datetime(2021, 3, 13, 23).replace(tzinfo=tz)
d1 = datetime(2021, 3, 14, 7).replace(tzinfo=tz)

CodePudding user response:

Thanks to the discussion on my original question and per the understanding I gained from the blog post by Paul Ganssle, I replaced my timedelta.total_seconds() math with:

d1.timestamp() - d0.timestamp()

This gives the proper 'actual' timespan value I was chasing.

  • Related