Search code examples
python-3.xunix-timestamp

Wrong Unix timestamp since April 2019 in Python 3.7


If, under Python 3.7:

from datetime import datetime
datetime(2019, 4, 1).timestamp()

I'm getting 1554073200.0. Shouldn't it be 1554076800.0 instead (i.e. 1 more hour) according to https://www.unixtimeconverter.io/list/2019/april?

I'm getting this error only after 1st April 2019. For instance, if I try:

datetime(2019, 3, 31).timestamp()

I get 1553990400.0, which I believe it's the expected result.

I'm using Spyder 3.3.6. Thank you for your help


Solution

  • The problem is that your datetime is "naïve". It doesn't know what timezone it's in. The timestamp method (as specified in the docs) is assuming you want the local timezone, which in your case has a DST change on the 31st March 2019. To get the answer you want, you need to set the timezone. For example,

    from datetime import datetime, timezone
    d = datetime(2019,4,1, tzinfo=timezone.utc)
    d.timestamp()
    

    which gives 1554076800.0 as you expected.