Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django settings USE_TZ, TIME_ZONE and django rest framework

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!

like image 415
nextdoordoc Avatar asked Jul 14 '16 03:07

nextdoordoc


People also ask

What is USE_TZ Django?

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?

What is the default timezone setting in Django?

Django's timezone is set to UTC by default. If your timezone is not UTC, you can change it using the procedure below: Open the setting.py file in the directory of our project.

How do I change timezone in Django settings py?

TIME_ZONE in Django The default timezone is TIME_ZONE = 'UTC' . TIME_ZONE = 'Asia/Calcutta' . For applying these changes we need to set the USE_TZ variable to TRUE.

How do I change the default date in Django?

If you want to be able to modify this field, set the following instead of auto_now_add=True : For DateField : default=date.today - from datetime.date.today() For DateTimeField : default=timezone.now - from django.utils.timezone.now()


1 Answers

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

like image 172
tutuDajuju Avatar answered Oct 13 '22 13:10

tutuDajuju