简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM