django settings 的時區和時間設置(django 默認生成時間總是差半個小時(或不等時間差)左右的問題)

目錄

問題描述:

問題研究:

第一部分:

第二部分:

解決方案:


問題描述:

當我們將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_ZONEUSE_I18N and USE_L10N.

百度翻譯結果:

一個布爾值,指定日期時間在默認情況下是否爲時區感知。如果設置爲True,Django將在內部使用時區感知日期時間。否則,Django將在本地時間使用原始日期時間。

解決方案:

所以按照django 的官方文檔的指示我們應該設置爲如下

TIME_ZONE = 'Asia/Shanghai'
USE_TZ = False
USE_I18N = True
USE_L10N = True

這樣時間就不會差了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章