在我的模型中,我有一个DateTimeField
说
class ReturnEvent(models.Model):
book_title = models.CharField()
return_time = models.DateTimeField()
例如,当我检索要打印的
return_time
时:return_event = ReturnEvent.objects.get(id=1)
print(return_event.return_time.strftime("%H:%M"))
我看到datetime 不知道时间,例如:
2016-06-18 08:18:00+00:00
但是,我喜欢使用strftime查看本地时间。
2016-06-18 10:18:00+02:00
有一个快速的解决方案吗?
最佳答案
如果您的设置中包含USE_TZ = True
,则Django在模板中进行渲染时,会将所有日期时间对象存储为UTC
,并将它们从TIME_ZONE=XYZ
即时转换为settings.py
。
这就是为什么从数据库中检索datetime
对象时区可识别,但是它的时区却带有UTC
(因此+00:00
中为2016-06-18 08:18:00+00:00
)。同样,您自己将时间转换为str
(并且未在模板中呈现),因此Django不会将其转换为TIME_ZONE
设置。您需要将其自己转换为所需的TimeZone。
如果要将其从TIME_ZONE
设置转换为TimeZone,可以执行
from django.utils import timezone
to_tz = timezone.get_default_timezone()
print return_event.return_time.astimezone(to_tz).strftime("%H:%M")
关于django - 在Django中检索支持时区的DateTimeField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37527186/