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 modelsclass Entry(models.Model):created = models.DateTimeField(auto_now_add=True)# ... more fields
from tastypie.resources import ModelResourcefrom myapp.models import Entryclass 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
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 ModelResourcefrom tastypie.serializers import Serializerclass MyDateSerializer(Serializer):"""Our own serializer to format datetimes in ISO 8601 but with timezoneoffset."""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:
Which is just what we wanted :)