python datetime's timestamp are different after replace timezone twice if original tz isn't utc

229 views Asked by At
from datetime import datetime

import pytz

tz = pytz.timezone("Asia/Singapore")

date_1 = datetime.now(tz=pytz.utc)
print(date_1.replace(tzinfo=tz).replace(tzinfo=pytz.utc).timestamp())
print(date_1.timestamp())

date_2 = datetime.now(tz=tz)
print(date_2.replace(tzinfo=pytz.utc).replace(tzinfo=tz).timestamp())
print(date_2.timestamp())

output:

1483599557.338336
1483599557.338336
1483603457.33842
1483599557.33842

why variable date_2's timestamps are different after tzinfo replaced twice?
since variable date_1 are the same.

1

There are 1 answers

0
hoozecn On

Time zones and offsets change over the years. The default zone name and offset delivered when pytz creates a timezone object are the earliest ones available for that zone, and sometimes they can seem kind of strange. When you use normalize to change the zone to a date, the proper zone name and offset are substituted. Simply using the datetime constructor to attach the zone to the date doesn't allow it to adjust properly.

tz.normalize(pytz.utc.normalize(date_2)).timestamp() == date_2.timestamp()