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?
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) }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With