编程语言
首页 > 编程语言> > python – Django DateTimeField存储datetime而不管tzinfo

python – Django DateTimeField存储datetime而不管tzinfo

作者:互联网

为什么django DateTimeFieldrestore tzinfo在datetime到< utc>?

下面是我的测试代码.

这是正常还是错.

如果是正常的,原因是什么?

models.py
class Date(models.Model):
  datetime = models.DateTimeField()


settings.py
TIME_ZONE = 'Asia/Seoul'
USE_TZ = True


test.py
from django.utils import timezone

datetime = timezone.localtime(timezone.localtimezone.now())
#now datetime is datetime.datetime(2015, 10, 22, 20, 31, 56, 248000, tzinfo=<DstTzInfo 'Asia/Seoul' KST+9:00:00 STD>)

models.Date(datetime=datetime).save()
#If I check datebase, It shows 2015-10-22 11:31:56.248000

model.Date.object.get(..)
#It returns datetime.datetime(2015, 10, 22, 11, 31, 56, 248000, tzinfo=<UTC>)

我期待django商店2015-10-22 20:31:56.248000并返回datetime.datetime(2015,10,22,20,31,56,248000,tzinfo =< DstTzInfo'Asia / Seoul'KST 9:00:00 STD&GT) – – – – – – – 编辑 – – – – – – – – 我用过Sqlite.

解决方法:

请务必阅读Django’s timezone documentation.在第一句中简洁地说明了这种方法:

When support for time zones is enabled, Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user’s time zone in templates and forms.

所以,是的,从UTC中看到数据库的返回值是正常的.

至于原因,文件说明:

Even if your Web site is available in only one time zone, it’s still good practice to store data in UTC in your database. The main reason is Daylight Saving Time (DST). Many countries have a system of DST, where clocks are moved forward in spring and backward in autumn. If you’re working in local time, you’re likely to encounter errors twice a year, when the transitions happen.

它还链接到pytz文档中的a more detailed description.

标签:python-datetime,python,timezone,datetime,django
来源: https://codeday.me/bug/20191003/1850133.html