Edit: This has now been recognized as a bug and it looks like a fix is in progress: https://github.com/tomchristie/django-rest-framework/issues/3732#issuecomment-267635612
I have a Django project where I expect the user to be in a certain timezone. I have TIME_ZONE = 'Asia/Kolkata'
and USE_TZ = True
in my settings.
I have a model that includes a datetimefield. When I first create the object, the modelserializer gives datetimes with a trailing +5:30
. Annoyingly, datetimes with auto_now_add=True
give UTC datetimes with a trailing Z
. I fixed this by making the field's default a callable for the current time.
If I serialize the object again at any point, all datetimes are in UTC with a trailing Z
. From the Django documentation, I would expect the serializer to use the current timezone, which defaults to the default timezone set by TIME_ZONE = 'Asia/Kolkata'
. I have checked the current timezone in my view with get_current_timezone_name()
and it is 'Asia/Kolkata'
. I have even tried using activate('Asia/Kolkata')
in my view, but times are still being returned in UTC.
Note that all the times are correct (the UTC times are 5:30 hours earlier), its just that I would expect for the times to be converted. All datetimes are stored in the DB as UTC times as expected.
Am I missing something or is this a bug with the Django Rest Framework serializers?
Have a look at the documentation here: http://www.django-rest-framework.org/api-guide/fields/#datetimefield
So getting the UTC (Z) representation of your datetime object is in fact default behaviour.
When you create or update a model instance through Djangorest, the serializer will be called with the
data
kwarg, which doesn't happen if you use the list or detail view.In both cases, your view will return
serializer.data
. In case of a create/update operation, this will be a representation ofserializer.validated_data
, while in case of a list/detail operation it'll be a direct representation of the instance.In both cases, the representation is achieved by calling
field.to_representation
with the default kwargformat=None
, which will make the field return the plain string value.The magic happens here:
isoformat()
method, and returned as-is.isoformat()
method, but DRF replaces+00:00
withZ
(see the link above).So to get the desired output with timezone offset, you could pass
format=None
or a custom strftime string to the DateTimeField in your serializer. However, you will always get the UTC time with+00:00
, because that's what the data is (fortunately) stored as.If you want the actual offset to
'Asia/Kolkata'
, you will probably have to define your ownDateTimeField
: