Home > Net >  Python datetime bug?
Python datetime bug?

Time:04-23

Ok, I am at a loss here. Is there any reason why an hour seems to be arbitrarily added to the date when converting to a timestamp and then converting back from a timestamp?

import datetime
dt = datetime.datetime(year=2020, month=3, day=8, hour=2)
print(dt)
dt2 = datetime.datetime.fromtimestamp(dt.timestamp())
print(dt2)

The output is:

2020-03-08 02:00:00
2020-03-08 03:00:00

HUH? Tested on 3.10.4 and 3.10.3

CodePudding user response:

Your code works fine on my computer, which is in Adelaide (Australia). The reason it doesn't on yours is that Daylight Savings time for the US EST time zone commenced on March 8th 2020, and so the clock switched forward from 2am to 3am at that time and thus the timestamp generated for 2am corresponds to an actual time of 3am (since 2am doesn't actually exist). If you try your code with hour=1 or hour=3 it will work fine.

You can resolve this issue by working solely with UTC time.

  • Related