Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

datetime - django localtime template filter doesn't work

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...