我以为 Django 创建了与时区无关的日期时间列,但当我查看我的 Postgres 表时,我发现那里记录的值有时区信息。
进一步我发现 Postgres 后端指示 Django 创建使用时区的列。
来自 django/db/backends/postgresql/creation.py:
data_types = {
...
'DateTimeField': 'timestamp with time zone',
...
架构显示创建的列被指定为“带时区的时间戳”。
CREATE TABLE notification_notice
(
...
created timestamp with time zone NOT NULL,
...
Postgres 日志显示已发送的更新语句。 Django 按照我的 Django 设置文件的指示构造了一个使用 UTC 作为时区的 SQL 语句。
UPDATE "notification_notice" SET "sender_id" = 1, "group_id" = NULL, "notice_type_id" = 1, "content_type_id" = 21, "object_id" = 3, "created" = E'2011-11-11 22:31:08.022148' WHERE "notification_notice"."id" = 14
这是我的 table 的样子。创建的列的时间戳的时区为“-08”。 Postgres 必须检查我的系统时钟的时区以找到时区。
my_db=# select * from notification_notice limit 1;
id | sender_id | group_id | notice_type_id | content_type_id | object_id | created | last_interaction_time
----+-----------+----------+----------------+-----------------+-----------+------------------------------+-----------------------
1 | | 3 | 21 | 53 | 6 | 2011-11-11 14:31:02.98882-08 |
(1 row)
问题:
Django 没有时区放手政策吗?
为什么 Postgres 后端对 models.DateTimeField 使用时区?这是 Postgres 要求的吗?
有没有办法强制 Django 在不使用时区的 Postgres 中创建时间戳列?
最佳答案
坏消息是问题的根源在于 Python 的日期时间实现。
好消息是 Django 有 an open ticket在这个问题上。
坏消息是2006年开了票
好消息是 recent proposal是更有用的读物,似乎正在开发中。包含提案的帖子很长,但信息量很大。
坏消息是提案归结为“这真是一团糟”。 (不过,它还在开发中。)
Going further I found that the Postgres backend directs Django to create columns that use time zones.
不,这是 Django 的设计决定。 PostgreSQL 仅存储 UTC;它不存储时区,也不存储偏移量。时区在概念上类似于一个环境变量,在插入或选择时间戳进行检索时将其应用于时间戳。
来自django developer's mail archive . . .
In the absence of actual time zone support in the database, any action taken by django is going to inconvenience somebody, and will likely not be compatible with non-django use of the same database.
这是个大问题——修复可能会使数据库与其他语言或框架不兼容。那绝对是我工作的地方。许多编程语言和框架访问数据库。
SQLite、Microsoft Access 和 MySQL(日期时间数据类型,而非时间戳)在该线程中被引用为数据库中缺少时区支持。
关于python - 为什么 Django 创建带有时区的 Postgres 时间戳列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8101506/