目录
问题描述:
当我们将django 的settings 时区设置为如下格式时
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = True
USE_I18N = True
USE_L10N = True
model 类设置了如下
create_time = models.DateTimeField('生成时间', default=timezone.now)
modify_time = models.DateTimeField('修改时间', auto_now=True) # 使用Model.save()来更新才会更新注意
这个时候产生的数据库时间会差将近半个小时的时间。为什么会产生这个原因呢?我们从djangod的官方文档中去找出答案。一共分为两个部分。
问题研究:
第一部分:
https://docs.djangoproject.com/zh-hans/2.1/ref/databases/#timestamp-columns
TIMESTAMP
columns¶
If you are using a legacy database that contains TIMESTAMP
columns, you must set USE_TZ = False
to avoid data corruption.inspectdb
maps these columns to DateTimeField
and if you enable timezone support, both MySQL and Django will attempt to convert the values from UTC to local time.
百度翻译结果:
“如果使用包含时间戳列的旧数据库,则必须设置USE_TZ = False
以避免数据损坏。InspectDB将这些列映射到DateTimeField,如果启用时区支持,MySQL和Django都将尝试将值从UTC转换为本地时间。”
第二部分:
https://docs.djangoproject.com/zh-hans/2.1/ref/settings/#std:setting-USE_TZ
USE_TZ
¶
Default: False
A boolean that specifies if datetimes will be timezone-aware by default or not. If this is set to True
, Django will use timezone-aware datetimes internally. Otherwise, Django will use naive datetimes in local time.
See also TIME_ZONE
, USE_I18N
and USE_L10N
.
百度翻译结果:
一个布尔值,指定日期时间在默认情况下是否为时区感知。如果设置为True,Django将在内部使用时区感知日期时间。否则,Django将在本地时间使用原始日期时间。
解决方案:
所以按照django 的官方文档的指示我们应该设置为如下
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = False
USE_I18N = True
USE_L10N = True
这样时间就不会差了