Jon Loyens RSS

Technologist, Tennis Fan, Musician

Archive

May
31st
Sun
permalink

The Python Twitter API, Timezones and PYTZ

In coding the open source Django Twitter Tribes app, I ran into what’s a pretty common problem for a lot of developers.  Alex Z, the designer of Bazaarvoice’s twitter page had created a wonderful skin for my tribes application.  However, one of the things he wanted to do was to list the Twitter status updates’ times using the nice, human readable format: ‘n hrs, m mins, d days ago’.  This presented me with a few problems that I had to overcome:

1) The Python Twitter API has a nice convenience function that allows you to get the time the status update was left in seconds.  This is a handy first step but in order to use Django’s ‘timesince’ filter, I needed a datetime object.  I accomplished this initially as follows:

for s in status_list:
s.created_at_as_datetime =         datetime.fromtimestamp(s.created_at_in_seconds)

(where status_list is the list of updates returned from the twitter API)

2) This worked but there was a side effect from the standpoint that the Twitter API returns time stamps in GMT.  When Python creates a new datetime object from a time stamp, it creates it by default in the local time of the machine.  This results in the time being significantly off when using the timesince filter.  What we need to do instead is create a datetime object in GMT.  In order to do this, you need to create a subclass of tzinfo.  Instead of doing this work though, we can use the PYTZ Python Timezone library instead like this:

for s in status_list:
s.created_at_as_datetime = pytz.utc.localize(datetime.fromtimestamp(s.created_at_in_seconds)).astimezone(pytz.timezone(‘US/Central’))

The PYTZ library is extremely useful for converting between timezones.  Essentially it has all the tzinfo subclasses for an entire database of timezones.  It makes working with timezones very easy.

  1. jonloyens posted this