Search code examples
pythondatetimetimedeltadst

Find timedelta difference with DST hours (Python)


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.


Solution

  • By default, Python's timedelta gives you wall-time difference for aware datetime objects (those that have a time zone attached) - not absolute time (in a physical sense; with the second as SI unit).

    To get a "DST aware" timedelta, first make sure the datetime objects are localized to a certain time zone (that has the DST). Then, you take into account the UTC offset of the two datetime objects; for example 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
    

    For further reading, I recommend the Semantics of timezone-aware datetime arithmetic blog post by Paul Ganssle.