Read time: 2 minutes

Displaying timezone-aware dates with Tastypie

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:

from django.db import models

class Entry(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    # ... more fields
from tastypie.resources import ModelResource
from myapp.models import Entry

class EntryResource(ModelResource):
    class Meta:
        queryset = Entry.objects.all()

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.

from tastypie.resources import ModelResource
from tastypie.serializers import Serializer

class MyDateSerializer(Serializer):
    Our own serializer to format datetimes in ISO 8601 but with timezone
    def format_datetime(self, data):
        # If naive or rfc-2822, default behavior...
        if is_naive(data) or self.datetime_formatting == 'rfc-2822':
            return super(MyDateSerializer, self).format_datetime(data)

        return data.isoformat()

class MyModelResource(ModelResource):

    class Meta:
        serializer = MyDateSerializer()

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 :)

Like what you read?

Subscribe to our newsletter and get updates on Deep Learning, NLP, Computer Vision & Python.

No spam, ever. We'll never share your email address and you can opt out at any time.
Comments powered by Disqus

Get in touch

Do you have a project in mind?
We'd love to e-meet you!

Thanks for reaching out!

We'll reply as soon as possible.

And in the meantime?
Check out our blog to see what we're currently working on.