Django DateTimeField存储日期时间,与tzinfo无关 [英] Django DateTimeField Stores datetime regardless of the tzinfo

查看:137
本文介绍了Django DateTimeField存储日期时间,与tzinfo无关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么将Django DateTimeField datetime 中恢复 tzinfo < utc>

Why django DateTimeFieldrestore tzinfo in datetime to <utc>?

下面是我的测试代码。

是正常还是错误??

如果正常,原因是什么?

If it is normal, what is the reason?

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>)

我希望d tores 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>)

I expect django stores 2015-10-22 20:31:56.248000 and return datetime.datetime(2015, 10, 22, 20, 31, 56, 248000, tzinfo=<DstTzInfo 'Asia/Seoul' KST+9:00:00 STD>)

-------- ------编辑----------------

--------------Edit----------------

我使用了 Sqlite

推荐答案

请确保您阅读 Django的时区文档。该方法在第一句话中简要说明:

Make sure you read Django's timezone documentation. The approach is succinctly stated in the very first sentence:


启用时区支持后, Django在UTC中存储日期时间信息在数据库中,内部使用时区感知的datetime对象,并将其以模板和形式转换为最终用户的时区。

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中看到数据库的返回值是正常的。

So, yes, it is normal that you see the return value from the database in UTC.

文档为何如此:


即使您的网站仅在一个时区中可用,将数据存储在数据库中的UTC仍然是一种好习惯。主要原因是夏令时(DST)。许多国家/地区采用夏令时制,时钟在春季向前移动,在秋季向后移动。如果您是在当地时间工作,那么当过渡发生时,您每年可能会遇到两次错误。

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 更详细的说明。 c $ c>文档。

It also links to a more detailed description in the pytz documentation.

这篇关于Django DateTimeField存储日期时间,与tzinfo无关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆