简体   繁体   English

django rest 框架与 postgresql 中的时区感知日期问题

[英]timezone aware dates issue in django rest framework with postgresql

I am using the Django rest framework with Postgresql.我正在使用 Django rest 框架和 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.从 Django 文档中,我了解到 Postgres 将仅以 UTC 存储日期时间,Django 在模板中显示时将其转换回本地时间。 However, I am not using templates.但是,我没有使用模板。 I am using DRF to create APIs which are consumed by a Vue app.我正在使用 DRF 创建 Vue 应用程序使用的 API。 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?如果值始终以 UTC 存储,为什么 Django Model 日期时间字段会转换为“带时区的时间戳”类型列?
  2. How to return DateTime values in local time from the Django rest framework.如何从 Django rest 框架返回本地时间的 DateTime 值。

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.特别注意 - 使用 django.utils.timezone.localtime(timezone.now()) 会在本地时间创建一个值,但在存储在数据库中时会转换回 UTC。

Any help will be highly appreciated.任何帮助将不胜感激。 Thanks a lot for your time and help.非常感谢您的时间和帮助。

To answer both your questions:要回答您的两个问题:

  1. This is the standard approach for TZ aware timestamps.这是 TZ 感知时间戳的标准方法。 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).如果存储为 UTC,如果我们有用户的时区(或默认的TIME_ZONE值),时间戳可以转换为任何本地时间表示。

  2. Django Rest Framework will use the settings defined for the app. Django Rest 框架将使用为应用程序定义的设置。 The docs for DateTimeField state: DateTimeField state 的文档

    default_timezone - A pytz.timezone representing the timezone. default_timezone - 代表时区的 pytz.timezone。 If not specified and the USE_TZ setting is enabled, this defaults to the current timezone.如果未指定并且启用了 USE_TZ 设置,则默认为当前时区。 If USE_TZ is disabled, then datetime objects will be naive.如果 USE_TZ 被禁用,那么 datetime 对象将是幼稚的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM