Home > front end >  django, python why timestamp changes after localize
django, python why timestamp changes after localize

Time:12-02

CODE:

import pytz
from django.utils import timezone

KST = pytz.timezone('Asia/Seoul')
UTC = pytz.timezone('UTC')

default_time = timezone.datetime(2021, 11, 29, 16, 44)

current_manual_kst = KST.localize(default_time)
current_manual_utc = default_time
print(current_manual_kst.timestamp())
print(current_manual_utc.timestamp())

RESULT:

>>> 1638171840.0
>>> 1638204240.0

So, I can see that results are different.

I thought timestamps should be the same but results are not.

Why this happened? And How to get the same timestamps (by default: UTC) from KST.localized datetime?

CodePudding user response:

A timestamp is expressed in UNIX time, which is the number of seconds since midnight January 1st 1970 UTC. In order to convert a datetime to such a UNIX timestamp, that datetime needs to be interpreted as some timezone. Because you can't express it relative to 1970 UTC without defining what timezone it's in. So if you have a naïve datetime object (without timezone) and take its timestamp(), it is interpreted as being in your local timezone and is converted to UTC from there.

And 16:44 in Seoul is apparently a different time than 16:44 in your computer's "local" timezone.

  • Related