/_next/static/media/placeholder-social.f0796e1f.png
blog
Displaying timezone-aware dates with Tastypie

Sat, Mar 16, 2013

So you have made the decision to use timezone-aware dates and now you are building your cool REST API using Tastypie. Of course timezones are important to your application, so you want to expose them when Tastypie exposes dates in the API.

You have a very simple resource that exposes a Django model that has an attribute, for example:

Out of the box, you notice that the dates displayed by Tastypie are converted to naive format, no matter if your USE_TZ variable is set to True in Django settings!

Searching the Internet you find that there is a Tastypie setting called TASTYPIE_DATETIME_FORMATTING. This might fix it...

Before, our timestamps were formatted like

  • 2013-02-28T16:42:55.08

If we set TASTYPIE_DATETIME_FORMATTING to 'rfc-2822' (it defaults to ISO-8601), our timestamps are now displayed like this

  • Thu, 28 Feb 2013 16:42:55 +0000

This is correct, but I think kind of ugly for an API (though good perhaps for email messages). I want my datetimes to be formatted using ISO-8601, but include the UTC offset. The solution? Write your own Tastypie serializer and override the behavior when serializing dates.

Of course, you now make all the resources in your application inherit from MyModelResource. Finally our dates will be printed like this:

  • 2013-02-28T16:42:55.08+00:00

Which is just what we wanted :)

Wondering how AI can help you?

This website uses cookies to improve user experience. Read more