【问题标题】:Unable to convert UTC timestamp to local time in templates无法在模板中将 UTC 时间戳转换为本地时间
【发布时间】:2020-11-19 17:29:24
【问题描述】:

我无法使用 Django 文档中提供的模板标签将此时间戳值转换为本地时间:

 {% load tz %}
 {% get_current_timezone as TIME_ZONE %}
 {{ private_message.timestamp|timezone:TIME_ZONE|date:'m/d/Y: h:i a' }}

我尝试了许多不同的模板标签,包括load localtime 等。无论如何,时间仍然显示为 UTC。

设置:

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

我在views.py中将时间戳保存为timezone.now()

任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: python django


    【解决方案1】:

    关键是,您的时区仍设置为 UTC。

    TIME_ZONE = 'UTC'
    

    所以,对于像 UTC+2 这样的东西,你可以使用

    TIME_ZONE = 'Europe/Istanbul'
    

    您可以访问所有有效时区here

    Reference

    编辑

    您可以尝试使用它来获取本地日期吗?

    from django.utils.timezone import localtime, now
    
    # get now datetime based upon django settings.py TZ_INFO
    localtime(now())
    

    【讨论】:

    • 但是没有办法以UTC格式存储数据,然后在模板中为用户本地转换时间吗?
    • @winston 你找到解决方案了吗?
    猜你喜欢
    • 2019-08-15
    • 2011-02-06
    • 2019-03-09
    • 2019-01-05
    • 2013-03-23
    • 2018-09-17
    • 1970-01-01
    • 2015-04-20
    • 1970-01-01
    相关资源
    最近更新 更多