Tom
Tom

Reputation: 22841

Django Timezone Support Outside of Templates

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?

Upvotes: 7

Views: 365

Answers (1)

supervacuo
supervacuo

Reputation: 9262

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())

Upvotes: 2

Related Questions