Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix timestamp to datetime in django with timezone

Tags:

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

like image 602
nknj Avatar asked Sep 25 '12 19:09

nknj


2 Answers

all methods above are valide, but not "django like". Here is a simple example, how a django programmer would do that:

from datetime import datetime  from django.utils.timezone import make_aware   # valid timestamp value = 1531489250  # you can pass the following obj to a DateTimeField, when your settings.USE_TZ == True datetime_obj_with_tz = make_aware(datetime.fromtimestamp(value)) 

See more utilites on the Django github timezone module to get whole overview...

like image 177
AntonTitov Avatar answered Oct 10 '22 21:10

AntonTitov


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) 
like image 38
David Wolever Avatar answered Oct 10 '22 21:10

David Wolever