Django's timezone-aware output apparently only applies when rendering a template. Is there a way to get that same auto-conversion to the currently active timezone for responses returning CSV or JSON?
Asked
Active
Viewed 355 times
7
-
Are you looking for a django setting? Or some python specific code? Perhaps try using pytz? – Matt Johnson-Pint Jul 18 '13 at 20:13
-
No, I'm looking to get the same auto-conversion behavior you see in a template when I send a CSV or JSON response to a user. – Tom Jul 18 '13 at 20:25
-
I don't believe there is any auto-conversion outside of templates... you will have to do it manually. – Ben Rosnick Aug 02 '13 at 19:36
-
Yeah, that's what I've found. Any idea where the logic that runs on templates happens? Obviously I can render the CSV and JSON via a template, but that stinks. – Tom Aug 03 '13 at 19:19
-
Got exactly the same issue here, thanks for asking. Too bad that its not supported, especially with the modern dynamic / javascript applications nowadays. – Maarten Kieft Jul 06 '17 at 15:54
1 Answers
2
It seems that the underlying function called to convert datetimes in templates is django.utils.timezone.template_localtime()
. Right next to it in the source is another utility function, localtime
, which looks like:
def localtime(value, timezone=None):
"""
Converts an aware datetime.datetime to local time.
Local time is defined by the current time zone, unless another time zone
is specified.
"""
...
So perhaps the following would work:
from django.utils.timezone import localtime, get_current_timezone
...
print localtime(obj.date_created, user.get_profile().timezone or get_current_timezone())

supervacuo
- 9,072
- 2
- 44
- 61