【发布时间】:2023-03-07 22:29:01
【问题描述】:
我使用 django 1.10 来显示日期时间。日期时间存储在 mongodb 中,它始终是没有时区信息的 UTC,所以我需要根据运行 django 的机器时区显示日期时间。
首先,在settings.py中添加这些
TIME_ZONE = 'Asia/Chongqing'
USE_I18N = True
USE_L10N = True
USE_TZ = True
然后在views.py中添加:
import pytz
from tzlocal import get_localzone
from django.utils import timezone
local_tz = get_localzone()
timezone.activate(local_tz)
# make datetime object and pass it to html to render
在模板.html中:
{% load tz %}
<table border="1">
{% for i in online %}
<tr>
<td align='center'>{{ i.time|localtime}}</td>
</tr>
{% endfor %}
</table>
但日期时间仍然是 UTC,即使我将 tzinfo 添加到传递到 html 的日期时间。
我错过了什么吗?
【问题讨论】:
-
模板中的“i”是时区感知的日期时间吗?尝试检查该日期时间对象的 tzinfo。