1
votes

I am using the Django rest framework with Postgresql. From the Django docs, I understood that Postgres will store the DateTime in UTC only and Django converts it back to the local time while displaying in the templates. However, I am not using templates. I am using DRF to create APIs which are consumed by a Vue app. I have two questions -

  1. Why Django Model DateTime fields are converted to "timestamp with time zone" type column if values are always stored in UTC?
  2. How to return DateTime values in local time from the Django rest framework.

Here is my settings File -

TIME_ZONE = 'Asia/Calcutta'

USE_TZ = True

REST_FRAMEWORK = {
    'DATE_INPUT_FORMATS': ["%d-%m-%Y",],
    'DATE_FORMAT': "%d-%m-%Y",
    'DATETIME_FORMAT': "%d-%m-%Y %H:%M:%S",
}

Special Note - using django.utils.timezone.localtime(timezone.now()) creates a value in localtime but it is converted back to UTC while storing in DB.

Any help will be highly appreciated. Thanks a lot for your time and help.

1

1 Answers

0
votes

To answer both your questions:

  1. This is the standard approach for TZ aware timestamps. From the docs:

    This is handy if your users live in more than one time zone and you want to display datetime information according to each user’s wall clock.

    If stored as UTC, the timestamp can be converted to any local time representation if we have the user's time zone (or the default TIME_ZONE value).

  2. Django Rest Framework will use the settings defined for the app. The docs for DateTimeField state:

    default_timezone - A pytz.timezone representing the timezone. If not specified and the USE_TZ setting is enabled, this defaults to the current timezone. If USE_TZ is disabled, then datetime objects will be naive.