Django DateTimeField Stores datetime regardless of the tzinfo

喜欢而已 提交于 2019-12-18 09:49:14

问题


Why django DateTimeFieldrestore tzinfo in datetime to <utc>?

Below is my test code.

Is it normal or wrong.?

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

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

I used Sqlite.


回答1:


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

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.

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

As for why, the documentation states:

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.

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



来源:https://stackoverflow.com/questions/33280135/django-datetimefield-stores-datetime-regardless-of-the-tzinfo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!