我使用 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的日期时间中。
我错过了什么?
为了使本地时间过滤器正常工作,您需要包括:
{% load tz %}
https://docs.djangoproject.com/en/2.2/topics/i18n/timezones/#std:templatefilter-localtime https://docs.djangoproject.com/en/2.2/topics/i18n/timezones/#std:templatefilter-localtime
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)