Django 时区配置

Django Timezone Configuration

我的 django 项目在设置中正确启用了时区。

但是,Django ORM 对象的 datetime 字段是一个简单的 datetime 对象,如块 3 所示。

预期结果应与块 4 的输出相同,无需任何手动转换。

In [1]: from django.conf import settings
   ...: settings.USE_TZ, settings.TIME_ZONE
Out[1]: (True, 'Asia/Hong_Kong')

In [2]: from qms.models import Quota

In [3]: q = Quota.objects.get(pk=1)
   ...: q.create_date, q.write_date
Out[3]:
(datetime.datetime(2021, 3, 10, 17, 37, 42, 489818),
 datetime.datetime(2021, 3, 10, 17, 37, 42, 489818))

In [4]: from django.utils import timezone
   ...: timezone.make_aware(q.create_date,timezone.utc), \
   ...: timezone.make_aware(q.write_date, timezone.utc)
Out[4]:
(datetime.datetime(2021, 3, 10, 17, 37, 42, 489818, tzinfo=<UTC>),
 datetime.datetime(2021, 3, 10, 17, 37, 42, 489818, tzinfo=<UTC>))

记录在SQL

Column value
id 1
create_date 2021-03-10 17:37:42.489818+00
write_date 2021-03-10 17:37:42.489818+00
name email

Django 模型定义

class Quota(models.models):
    name = models.CharField(max_length=255)
    create_date = models.DateTimeField(auto_now_add=True)
    write_date = models.DateTimeField(auto_now=True)

PostgreSQL 数据库模式和设置,Table“public.qms_quota”

Column Type Modifiers
id integer not null default nextval('qms_quota_id_seq'::regclass)
create_date timestamp with time zone not null
write_date timestamp with time zone not null
name character varying(255) not null
SHOW TIMEZONE;
 TimeZone
----------
 UTC

问题

  1. 如何在不进行任何转换的情况下直接获取时区感知的日期时间对象?
  2. 或者需要手动转换?

您可以使用django.utils.timezone.localtime将从数据库接收到的日期时间转换为本地时间:

from django.utils.timezone import localtime
q = Quota.objects.get(pk=1)
print(localtime(q.create_date), localtime(q.write_date))

根本原因是连接池库中的错误 django_postgrespool2==2.0.1

当您将连接引擎与“django_postgrespool2”一起使用时,它将不会正确处理时区设置。 Releated Issue

TLDR:使用引擎 django.db.backends.postgresql