Search code examples
pythondatetimetimezoneunix-timestamputc

Why do a timezone-unaware and a timezone-aware datetime object with a different timezone yield the same unix-timestamp?


So, as far as I understand if you convert without a timezone from or to a unix-timestamp you will always get GMT/UTC, like this:

import datetime
import pytz
datetime.datetime(2020,4,1,0,0,0).timestamp()

The resulting timestamp is 1585692000.

Now if I do this:

(pytz.timezone("Europe/Berlin").localize(datetime.datetime(2020,4,1,0,0,0))).timestamp()

It yields the same unix-timestamp.

If I enter a datetime and tell the program that this datetime has the timezone GMT+1 then its UTC value should be offset by 1 hour, and since a unix-timestamp is always UTC it should be different as well, but it's the same.

Why? Which of my assumptions is wrong?


Solution

  • UNIX timestamps have no timezone, they always express the number of seconds elapsed since Jan. 1st 1970 00:00 UTC. That number is the same globally, it doesn't change with your timezone.

    Naive datetime instances are assumed to represent local time and [timestamp] relies on the platform C mktime() function to perform the conversion.

    https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp

    So, if you are in Europe/Berlin, then a naïve datetime and a datetime localised to Europe/Berlin are interpreted the same way when converted to a timestamp. Try localising to other timezones, which means that 2020, 4, 1, 0, 0, 0 actually refers to a different time, and you'll see different timestamps as well.