ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python – Django DateTimeField存储datetime而不管tzinfo

2019-10-03 15:06:21  阅读:464  来源: 互联网

标签:python-datetime python timezone datetime django


为什么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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有