问题
I am use django 1.10 to display datetime. The datetime is stored in mongodb and it is always UTC without timezone info, so I need to display the date time according to machine's time zone which run django.
First, add those in settings.py
TIME_ZONE = 'Asia/Chongqing'
USE_I18N = True
USE_L10N = True
USE_TZ = True
Then in views.py adds:
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
in template.html:
{% load tz %}
<table border="1">
{% for i in online %}
<tr>
<td align='center'>{{ i.time|localtime}}</td>
</tr>
{% endfor %}
</table>
But the datetime still UTC, even I add tzinfo to the datetime which pass into html.
Did I miss something?
回答1:
In order for the localtime filter to work, you need to include:
{% load tz %}
https://docs.djangoproject.com/en/2.2/topics/i18n/timezones/#std:templatefilter-localtime
来源:https://stackoverflow.com/questions/39653750/django-localtime-template-filter-doesnt-work