[Django]-How to show local time in template

5👍

Supposing that all your datetimes are right stored in database as UTC, you can use tz django utility in your template to cast your date to your local time

IE if a datetime is stored as Oct 12, 2017 18:00:00 and i want to convert it to America/La_Paz local time (GMT -4) i can use

Session: start time {{ item.session.started_at|timezone:"America/La_Paz" }}

And in the template will show the local time to America/La_Paz (Oct 12, 2017 14:00:00 in this case)

templates/my_template.html

{% load tz %}
<!-- some html code here -->
Session: start time {{ item.session.started_at|timezone:"America/La_Paz" }}

You can create a cotext var or a var in your view to set the timezone that you wnat to use to cast the date in the tmeplate, ans use it to do the cast

in your view: my_timezone = 'A VALID TIMEZONE NAME'

and again in your template

templates/my_template.html

{% load tz %}
<!-- some html code here -->
Session: start time {{ item.session.started_at|timezone:my_timezone}}

3👍

After finding the user’s timezone, do this in Django 2 and beyond:

{% load tz %}
{% timezone "Europe/Paris" %}
    Paris time: {{ object.date }}
{% endtimezone %}
👤scott

2👍

If I’m not mistaken the TIME_ZONE setting sets the “local” timezone, so change that from UTC to your local time zone.

There is no HTTP-Header that shows the server the client’s time zone. Most websites that use localized times ask the user what timezone they are in and save that in the users profile. See Django Documentation
https://docs.djangoproject.com/en/2.0/topics/i18n/timezones/#selecting-the-current-time-zone

Javascript has a way of accessing the UTC offset, maybe you can use that to send the information to your server along with the request.

👤Tim

0👍

The users of your webapp may be in different time zones, so the conversion to an appropriate time zone is necessary. You can create a middleware and use activate function to set the current time zone. To get the appropriate time zone you can do an ajax api call to Free IP Geolocation API in your landing page and the time zone value can be saved in a cookie variable which can be later accessed in the middleware.

landingpage.html

<script>
$.ajax({
        url: 'https://freegeoip.app/json/',
        dataType: 'json',
        success: function (data) {
            document.cookie = 'timezone=' + data['time_zone'] + '; path=/';
        }
      });
</script>

middleware.py

import pytz
import requests

from django.utils import timezone

class TimezoneMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

def __call__(self, request):
    
    tzname = request.COOKIES.get('timezone')
    if tzname:
        timezone.activate(pytz.timezone(tzname))
    else:
        timezone.deactivate()
    return self.get_response(request)

settings.py

MIDDLEWARE = [      ........
            'projectname.middleware.TimezoneMiddleware',

]

Leave a comment