我有 django 1.7.x 项目。我通过 shell 插入新数据如下:
from polls.models import Question, Choice
from django.utils import timezone
q = Question(question_text = "What's new?", pub_date = timezone.now(), status = True)
q.save()
q.pub_date
但是,我发现日期设置为 UTC。因此,在项目设置中,我将时区更改为 TIME_ZONE = 'Africa/Cairo'
。但是,通过 q.pub_date = timezone.now()
通过 manage shell
从项目的 shell 更新记录不会将记录的时区更改为新时区。它比我开发的计算机少两个小时,开罗时区和 UTC 之间的差异。我能错过什么?
最佳答案
来自 the documentation :
Note that
now()
will always return times in UTC regardless of the value ofTIME_ZONE
; you can uselocaltime()
to convert to a time in the current time zone.
但请注意,Django 始终以 UTC 格式存储日期时间,因此即使您使用 localtime()
转换它也不会影响值的存储方式。因此 q.pub_date
将采用 UTC 或数据库(而非 Django)设置中定义的时区。
但重要的是日期时间如何呈现给用户,以及 timezone documentation 中描述的控制方式。 .
关于python - Django 时区设置更改不影响模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27642356/