简体   繁体   中英

timezone aware datetime for django using templates

I've been working on a small problem in django and I havent quite been able to figure it out . I have a django app running on a godaddy vps and in views.py i have these lines as part of a function definition

    currtime=datetime.datetime.now()
            return render_to_response('test.html',{'currtime' : currtime })

Now in my test.html, im using templates to get currtime

          {% load tz %}
          {% localtime on %} 
          <p>{{currtime}}</p>
          {% endlocaltime %}

I believe the point of timezone aware datetime objects in django is to automatically convert the time to the LOCAL time when rendering the HTML via the templates.. As you can see above i have loaded the pytz library and enabled localtime... Even though I'm in India I still get a current time value which is the same as the time in Texas which is in CDT . The reason why I want this to work is that , I have a database with datetime stored in UTC and I would like the time to be displayed in local time(ie convert from UTC to local time ) based on the user's geographical location . Any help would be appreciated , thank you.

I just got here accidentally googling for a related problem, but I thought I'd answer, just in case someone finds it as well...

What you were after didn't work, because localtime means the local time on the server (expressed in the timezone as defined in your settings). The django app running on the server has no way of figuring out what the client's timezone is. You should detect the timezone in the browser, eg using jstz .

A more robust solution is to let the users choose their own timezone, but also setting the selection using autodetection (so that most of the time they can just press OK). Then of course you can store this on the server and from that point on, you can generate your templates using the user's timezone:

{% loadtz %}
{% timezone user.timezone %}
.....
{% endtimezone %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM