How to show time value based on user's time zone using Django template tags

Question:

I’m saving all timing to my database in ‘UTC’ time zone, but I want every user to see this value converted to his own timezone. is it possible to be used in Django?

my settings.py :

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

Here is what I tried:

{% load tz %}
<p>
Leave on {{ request.date_time.date|localtime }}  at {{ request.date_time.time|localtime }}
</p>

But it gives me a blank result, and when I remove the |localtime part, it shows it in the UTC format. any help with this?

Asked By: Ahmed Wagdi

||

Answers:

You can also convert your timezone into the user’s timezone from Django view and pass it in context and use that context in your template as below…

views.py

from django.utils import timezone
local_time = timezone.localtime(your_datetime_object)

Now, you can pass local_time into your context and use it in your template.

For more reference, you can click here

Answered By: MK Patel

localtime template tag does not operate on date object. It operates on datetime object. You should apply it on datetime object and then chain with date filter.

{{ request.date_time|localtime|date:'Y-m-d' }} at {{ request.date_time|localtime|date:'H:i' }}

Or you can do

{% with local=request.date_time|localtime %}
  <p>
    Leave on {{ local|date:'Y-m-d' }} at {{ local|date:'H:i' }}
  </p>
{% endwith %}
Answered By: Nafees Anwar
def get_publish_timezone(self):
    import pytz
    return self.publish.astimezone(pytz.timezone(self.author.get_timezone_str())).replace(tzinfo=None)

here get_timezone_str() is the one who convert id of timezone to string like ‘Asia/Kolkata

def get_timezone_str(self):
    from .timezone import from_system
    try:
        return from_system[self.timezone]
    except KeyError:
        return 'UTC'

from_system is dict some demos are below.

from_system = {0: 'America/Puerto_Rico',
1: 'America/New_York',
2: 'America/Chicago',
3: 'America/Denver',
}
Answered By: nuit
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.