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

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.9k views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...