Unix timestamp to datetime in django with timezone

nknj picture nknj · Sep 25, 2012 · Viewed 27.8k times · Source

I have a javascript calendar that is sending me a unixtimestamp. I am in Singapore. I want this timestamp to be interpreted as a Singapore timestamp and then converted to utc for comparisons with the db.

I cant, for the life of myself, figure out how to tell django that this time stamp is from the current timezone, Singapore.

When i do a print statement of the timestamp, it adds 8 hours to the time (which means that django thinks I input the time in utc and is localizing it to the Singaporean context)

Among many other things, I tried: start=datetime.datetime.fromtimestamp(int(start_date)).replace(tzinfo=get_current_timezone())

The start_date is 1325376000 (which translates to 2012-01-01 00:00:00)

However,when i print the output of this I get 2012-01-01 08:00:00+06:55. I dont even know where +06:55 is coming from when singapore is +08:00. I am SO lost.

Thanks for your help.

settings.py:

TIME_ZONE = 'Asia/Singapore'

USE_TZ = True

Answer

David Wolever picture David Wolever · Sep 25, 2012

Assuming you've got pytz installed:

from datetime import datetime
import pytz
local_tz = pytz.timezone("Asia/Singapore") 
utc_dt = datetime.utcfromtimestamp(timestamp).replace(tzinfo=pytz.utc)
local_dt = local_tz.normalize(utc_dt.astimezone(local_tz))

For example:

>>> from datetime import datetime
>>> import pytz
>>> local_tz = pytz.timezone("Asia/Singapore")
>>> utc_dt = datetime.utcfromtimestamp(1325376000).replace(tzinfo=pytz.utc)
>>> utc_dt
datetime.datetime(2012, 1, 1, 0, 0, tzinfo=<UTC>)
>>> local_dt = local_tz.normalize(utc_dt.astimezone(local_tz))
>>> local_dt
datetime.datetime(2012, 1, 1, 8, 0, tzinfo=<DstTzInfo 'Asia/Singapore' SGT+8:00:00 STD>)
>>> local_dt.replace(tzinfo=None)
datetime.datetime(2012, 1, 1, 8, 0)