Our Blog

0

I won’t have to pencil out that when working with dates, that timezone-awareness is crucial.
Here are two pages you might want to look at if that is new for you:

Though I’ve had some headaches the last 24 hrs getting it working with timestamps.
In my (Socify.it) project I’m using timestamps to recieve a (Unix) timestamp through a webservice and have to find a specific file on a FTP server matching that timestamp, with in another format (like “cam1-%Y-%m-%d-%H-%M-%S.jpg“).

Your timestamps must be ‘neutral’. Afterwards you can extract a time-zone dependent date-time.

Just using datetime.utcfromtimestamp(timestamp) will set a date determined by what you have in you Django settings’s TIME_ZONE.
You’ll need to ‘normalize it’ with the timezone that has saved that date-time.

>>> import pytz
>>> from datetime import datetime
>>> from django.utils.timezone import utc
>>> timestamp = 1353574755
>>> tz = 'Australia/Sydney'
>>> tz = pytz.timezone(tz)
>>> utc_dt = utc.localize(datetime.utcfromtimestamp(timestamp))
>>> e_dt = tz.normalize(utc_dt.astimezone(tz))

Now let’s do that the other way around. In this example I’ll try to keep the timestamp ‘neutral’, in order to be able to extract a time-zone dependent date-time, later on : Calendar.timegm() is our friend here, where time.mktime() isn’t.

Let’s import that and try:

>>> import calendar
>>> utc_dt = utc.localize(datetime(2012, 11, 24,0,0,0))
>>> timestamp = calendar.timegm(utc_dt.timetuple())

Check yourself by converting it back. Also try time.mktime() in stead of calendar.timegm() and see the unwanted difference!