I understand that the best practice now with Django 1.4 is to store all datetime
in UTC and I agree with that. I also understand that all timezone conversation should be done in the template level like this:
{% load tz %}
{% timezone "Europe/Paris" %}
Paris time: {{ value }}
{% endtimezone %}
However, I need to convert the UTC time to the request
's local time all in Python. I can't use the template tags since I am returning the string in JSON using Ajax (more specifically Dajaxice).
Currently this is my code ajax.py
:
# checked is from the checkbox's this.value (Javascript).
datetime = timezone.now() if checked else None
$ order_pk is sent to the Ajax function.
order = Order.objects.get(pk=order_pk)
order.time = datetime
order.save()
return simplejson.dumps({
'error': False,
'datetime': dateformat.format(datetime, 'F j, Y, P') if checked else 'None'
})
So even if the current time is April 14, 2012, 5:52 p.m.
in EST time (my local timezone), the JSON response will return April 14, 2012, 9:52 p.m
, because that is the UTC time.
Also I noticed that Django stores a template variable called TIME_ZONE
for each request (not actually part of the request
variable), so since my is America/New_York
, I'm assuming that Django can figure out each visitor's own local timezone (based on HTTP header)?
Anyway, so my question is two-fold:
- How do I get the visitor's local timezone in my
ajax.py
? (Probably pass it as a string argument like {{ TIME_ZONE }}
)
- With the visitor's local timezone, how to convert the UTC
timezone.now()
to the local timezone and output as a string using Django's dateformat
?
EDIT: for @agf
timezone.now()
gives the UTC time when USE_TZ = True
:
# From django.utils.timezone
def now():
"""
Returns an aware or naive datetime.datetime, depending on settings.USE_TZ.
"""
if settings.USE_TZ:
# timeit shows that datetime.now(tz=utc) is 24% slower
return datetime.utcnow().replace(tzinfo=utc)
else:
return datetime.now()
Is there anyway to convert a datetime
to something other than UTC? For example, can I do something like current_time = timezone.now()
, then current_time.replace(tzinfo=est)
(EST = Eastern Standard Time)?
See Question&Answers more detail:
os