3

I'm using PostgreSQL to store an object with a DateTimeField.
The DateTimeField is using auto_now_add options.
And it is created automatically from serializer in Django Rest Framework.

As described in Django docs, I tried to get local timezone and activate it.

from django.utils.timezone import localtime, get_current_timezone

tz = get_current_timezone()
timezone.activate(tz)
session.started_at = localtime(session.started_at)

In template index.html, I also try to load timezone.

{% localtime on %}
   Session: start time {{ item.session.started_at }} 
{% endlocaltime %}

In settings.py

USE_TZ = True
TIME_ZONE = 'UTC'

I'm using GMT+7 timezone but it still shows UTC time on template.

I'm using Django development server to test.

Am I missing something?

ayhan
  • 70,170
  • 20
  • 182
  • 203
Phu Nguyen
  • 261
  • 3
  • 6
  • 1
    Why wouldn't it? You set the timezone to UTC? Your client (the browser) is in GMT+7, but Django doesn't know that. – Bailey Parker Jan 22 '18 at 14:21
  • As described [here](https://docs.djangoproject.com/en/1.11/topics/i18n/timezones/#default-time-zone-and-current-time-zone), it's the default timezone. There is `current time zone` which is used for rendering. – Phu Nguyen Jan 22 '18 at 14:30
  • 1
    Possible duplicate of [Get local timezone in django](https://stackoverflow.com/questions/14657173/get-local-timezone-in-django) – Bailey Parker Jan 22 '18 at 14:33

4 Answers4

4

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}}
Angel F
  • 479
  • 3
  • 13
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
  • 1,194
  • 7
  • 18
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
  • 1,272
  • 11
  • 28
  • Thanks for your reply. So how can I show the exact local time for users in different timezones? – Phu Nguyen Jan 22 '18 at 14:26
  • I don't think there is an easy way to determine the user timezone. See the following 2 links: https://docs.djangoproject.com/en/2.0/topics/i18n/timezones/#selecting-the-current-time-zone https://stackoverflow.com/questions/10235956/django-1-4-how-to-automatically-get-users-timezone-from-client – Tim Jan 22 '18 at 14:30
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',

]

Arun Baby
  • 11
  • 1