Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python datetime bug?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading