为什么时间仍然显示UTC时区而不是设置。TIME_ZONE? [英] Why does time still show with UTC time zone instead of settings.TIME_ZONE?
问题描述
我有一个模型,该模型在模型的 __ str __()
方法中显示短字符串
I have a model that shows a short string in __str__()
method of the model
def __str__(self):
return "Scheduled at %s" % (self.date_time.strftime("%B %d %Y %I:%M %p"))
#Output: <Task: Scheduled at September 30 2018 12:30 AM>
# it should have been: <Task: Scheduled at September 29 2018 08:30 PM>
当我去 Django管理员时,在标题任务:计划在2018年9月30日上午12:30 ,并在输入中填充正确的 TIME_ZONE
: 20:30:00
When I go to the Django admin, I see in the title Task: Scheduled at September 30 2018 12:30 AM and in the input it is filled with the correct TIME_ZONE
: 20:30:00
settings.py
TIME_ZONE = 'Etc/GMT+4'
USE_I18N = False
USE_L10N = False
USE_TZ = True
他一直显示UTC时区的时间,但是我设置 TIME_ZONE ='Etc / GMT + 4
。
He keeps showing time with UTC time zone, however I set TIME_ZONE='Etc/GMT+4
in my settings.
我希望将时间数据以UTC格式保存在数据库中,并以TIME_ZONE显示,在我的情况下为 Etc / GTM + 4
I want time data to be saved in database as UTC and show them with TIME_ZONE, in my case Etc/GTM+4
推荐答案
Django在使用模板显示值。如果要在任意代码块中进行转换,请使用 localtime()
助手:
Django converts datetimes when displaying values with templates. If you want to do the conversion in arbitrary blocks of code, use the localtime()
helper:
from django.utils.timezone import localtime
def __str__(self):
return "Scheduled at %s" % localtime(self.date_time).strftime("%B %d %Y %I:%M %p")
这篇关于为什么时间仍然显示UTC时区而不是设置。TIME_ZONE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!