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?
Asked
Active
Viewed 1,176 times
1 Answers
0
You need to start using Django's Time Zones:
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:
- Selecting the current time zone (has the view-to-template example)
- When should I activate/deactivate the current timezone in Django (1.4)?
- How do I get the visitor's current timezone then convert timezone.now() to string of the local time in Django 1.4?
Hope that helps.
-
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