Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python / Django templates timezone issue

I am having the following issue, and cant figure out what i am missing here.

I have enabled the Timezone in the settings.py

Settings.py

TIME_ZONE = 'America/Chicago'

USE_TZ = True

Use-case

Now, when I have created an object at 3.15pm (Local time), and i get the following date stored in my created_at field in database.

created_at = models.DateTimeField(auto_now_add=True)

2014-12-12 11:03:48

When i render that date in my templates i get the following value.

{{ image.created_at }} = > Dec. 12, 2014, 5:03 a.m.

TEST CASE

    from datetime import datetime
    from dateutil.tz import tzutc, tzlocal

    utc = datetime.now(tzutc())
    print('UTC:   ' + str(utc))

    local = utc.astimezone(tzlocal())
    print('Local: ' + str(local))

I am getting correct datetime here. And when i use myobject.created_at.astimezone(tzlocal()) it also returns correct. but its when in Templates i get 1 hour ahead time. WHY? i tried both |local filter also but no use

What am I missing?

like image 269
A.J. Avatar asked Dec 01 '22 00:12

A.J.


1 Answers

Add the below snippet to the base.html

{% load tz %}

{% timezone "Asia/Kolkata" %}
  <All content goes here>
{% endtimezone %}

Inherit this to all templates. Everything render in 'Asia/Kolkata' time zone

like image 145
Sathish Kumar Avatar answered Dec 05 '22 14:12

Sathish Kumar