Django settings USE_TZ, TIME_ZONE and django rest framework

nextdoordoc picture nextdoordoc · Jul 14, 2016 · Viewed 14.8k times · Source

In Django tutorials, there is a sentence described like below.

TIME_ZONE

...

When USE_TZ is False, this is the time zone in which Django will store all datetimes. When USE_TZ is True, this is the default time zone that Django will use to display datetimes in templates and to interpret datetimes entered in forms.

...

When django rest framework takes the naive datetime data from request. Then Django will interpret this naive datetime to aware local datetime of TIME_ZONE setting? And if it is right, how does it work?

Thanks in advance!

Answer

tutuDajuju picture tutuDajuju · Jul 15, 2016

Generally, an input timezone is determined in DRF while parsing the request in the serializer's DateTimeField (similar to form fields).

You can control the format of such input, and there's even a general setting DATETIME_INPUT_FORMATS which defaults to ['iso-8601'].

This basically means that the input can both omit and specify the time zone using the ISO-8601 format and the field will generally be able to determine whether to create an aware or naive datetime object, according to your Django settings.

It will not attempt to convert a naive datetime to aware if timezone attribute is set to None, nor will it attempt to convert an aware timezone to a naive if the attribute is not None.

The attribute defaults to TIME_ZONE if USE_TZ is True, otherwise it is None; and can also be overridden explicitly, in a field initialisation.

note: someone should send a PR to DRF to document this behavior.

For more info see Django's time zone documentation