【问题标题】:Why does time still show with UTC time zone instead of settings.TIME_ZONE?为什么时间仍然显示 UTC 时区而不是 settings.TIME_ZONE?
【发布时间】:2019-03-05 12:07:26
【问题描述】:

我有一个模型在模型的__str__() 方法中显示一个短字符串

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 管理员 时,我在标题中看到 Task: Scheduled at September 30 2018 12:30 AM 并在输入中填充了正确的TIME_ZONE20:30:00

settings.py

TIME_ZONE = 'Etc/GMT+4'

USE_I18N = False

USE_L10N = False

USE_TZ = True

他一直以 UTC 时区显示时间,但我在设置中设置了 TIME_ZONE='Etc/GMT+4

我希望将时间数据以 UTC 格式保存在数据库中,并以 TIME_ZONE 显示,在我的情况下为 Etc/GTM+4

【问题讨论】:

    标签: python django datetime pytz django-timezone


    【解决方案1】:

    Django 在displaying values with templates 时转换日期时间。如果您想在任意代码块中进行转换,请使用 localtime() 助手:

    from django.utils.timezone import localtime
    
    def __str__(self):
        return "Scheduled at %s" % localtime(self.date_time).strftime("%B %d %Y %I:%M %p")
    

    【讨论】:

    • 谢谢!我也设置了TIME_ZONE,是多余的吗? django.utils.timezone.localtime(date_time, pytz.timezone(settings.TIME_ZONE))
    • 这是多余的。文档说默认值是当前时区,如果您还没有激活另一个时区,则与TIME_ZONE相同。
    猜你喜欢
    • 2015-04-28
    • 2023-04-02
    • 2019-09-20
    • 2020-12-17
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 2010-09-21
    • 2012-02-14
    相关资源
    最近更新 更多