python-dateutil

python datetul timezone results in a wrong hour


I used datetul to take care of daylight-saving hour, but when I calculate datediff it results in a wrong calcualation. In the code below, I used "America/New_York" but the diff between dt_159_dateutiland dt_300_dateutil supposed to be 1 second but it is 3601 seconds. I set timeshift manually, result was 1 second.

from datetime import date,timedelta,datetime,timezone
from dateutil import tz


# using dateutl pacage
eastern=tz.gettz("America/New_York")

dt_159_dateutil=datetime(2023,3,12,1,59,59,tzinfo=eastern)
dt_300_dateutil=datetime(2023,3,12,3,0,0,tzinfo=eastern)

# set houst shift manually
est=timezone(timedelta(hours=-5))
edt=timezone(timedelta(hours=-4))
dt_159=datetime(2023,3,12,1,59,59,tzinfo=est)
dt_300=datetime(2023,3,12,3,0,0,tzinfo=edt)



display((dt_300-dt_159).seconds)
# output 1

display((dt_300_dateutil-dt_159_dateutil).seconds)

Solution

  • Thanks, I figured out the issue. In the case of dateutil the created datetime is aware of timezone, so to do date diff correctly I need to convert them to utc then apply the diff.

    diff=dt_300_dateutil.astimezone(tz.UTC)-dt_159_dateutil.astimezone(tz.UTC)
    # out put 1 second