1

I want to format a datetime to the user's localtime. I do not want to do it in a template though, I want to do it in the .py file and pass it to the template for display as is. What facility do the template code use to do this? Can I get at this from my .py file?

pbx
  • 689
  • 1
  • 10
  • 22

1 Answers1

0

You need to start using Django's Time Zones:

  • set USE_TZ to True
  • install pytz module (recommended)
  • set the default TIME_ZONE

Then, in order to make time-zone-aware datetimes, you need to somehow determine the user's timezone. The most reliable way would be to let the user choose the timezone and remember the choice for every user. Then, in the view activate the specific user's timezone:

import pytz
from django.utils import timezone

tzname = request.session.get('django_timezone')  # or wherever you store the user's timezone
if tzname:
    timezone.activate(pytz.timezone(tzname))
else:
    timezone.deactivate()

print timezone.now()

Also see:

Hope that helps.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • I don't understand why you say let the user choose his timezone. How does the template convert to the user's local timezone? It must know the user's timezone. – pbx Jun 11 '14 at 05:49
  • @pbx the idea is to get the user's timezone: either let the user choose it, or determine it automatically (see [this answer](http://stackoverflow.com/a/9962801/771848)). Then, activate it in the view using `timezone` from `django.utils`. – alecxe Jun 11 '14 at 13:41