Tay Ray Chuan home archive

timezone support in bloggart

Thu, 3 Jun 2010 02:45:06 +0800 | Filed under bloggart, gae

I wanted to localize this blog to my timezone - after all, I live here, and not in a UTC region.

But this needed some work. Most GAE python developers (no pun intended) would have noticed the lack of timezone-awareness for datetime properties.

To add timezone-awareness in bloggart, I had to find the various instances of datetime.datetime.now(), as well as usage of the datetime properties, BlogPost.published and BlogPost.updated.

Handling now() was easy - I just gave it an instance of my tzinfo implementation. The second one was much harder - I had to spend considerable eyeball-time to spot areas where timezone-awareness was needed, and replace these with timezone-aware companions.

For example, the timezone-aware companion to 'BlogPost.published' would look like this (adapted):

  @property
  def published_tz(self):
    tz = utils.tzinfo()
    return self.published.replace(tzinfo=UTC()).astimezone(tz)

Notice the replace() on the datetime - GAE returns 'naive' datetime instances, so you have to set tzinfo on them, even if the offset is just 0.

Now - the easy part: specifying which timezone to use.

The GAE docs - indeed, the official python docs too - points us to the behmoth of a pytz. Perhaps this has got to do with python's hands-off approach to timezones - time.tzset() is available only on Unix.

After some grumbling (why can't I just do `time_zone("Asia/Singapore")???), I wrote a datetime.tzinfo implementation for my timezone (Singapore, +8 GMT). It's unbelievably simple, that I don't understand why I have to write it in the first place. (There I go grumbling again....)

Check it out in my rc/tz branch. If you want to use it, you'll have to write a tzinfo implementation for your own timezone.

blog comments powered by Disqus