Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying local time using DateTimeFields in Jinja2 templates - Django

When using Django and Jinja2, it seems that datetime objects don't get converted to the local timezone automatically, even if USE_TZ=True. Instead, the value remains in UTC.

I was able to solve this by creating a filter that runs localtime() on the values.

However, I am not sure how to do the same thing with DateTimeFields. In the template, I have {{ field }}, where field is the DateTimeField, but there is nowhere to put a filter.

What is the best way to convert DateTimeField values to the current timezone?

like image 267
user3033028 Avatar asked Apr 23 '14 18:04

user3033028


1 Answers

Thankfully this is a relatively easy fix. Django provides a function named template_localtime that (according to the documentation) does the following:

"Checks if value is a datetime and converts it to local time if necessary."

Exposing this to Jinja2 templates involves either the creation of a template filter or a global function. This example demonstrates both:

from django.utils.timezone import template_localtime

env = Environment(**kwargs)
env.filters.update({
    'localtime': template_localtime,
})
env.globals.update({
    'localtime': template_localtime,
})

You can then use these in a Jinja2 template as follows:

{{ item.date|localtime }}
{{ localtime(item.date) }}
like image 56
Nathan Osman Avatar answered Nov 12 '22 09:11

Nathan Osman