Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 624
Tom Avatar asked Jul 18 '13 19:07

Tom


People also ask

How do I enable timezone in Django?

Time zone support is disabled by default. To enable it, set USE_TZ = True in your settings file. In Django 5.0, time zone support will be enabled by default. Time zone support uses zoneinfo , which is part of the Python standard library from Python 3.9.

What is Use_tz in Django?

When USE_TZ is True, this is the default time zone that Django will use to display datetimes in templates and to interpret datetimes entered in forms. ... When django rest framework takes the naive datetime data from request.

How do I change the default timezone in Django?

TIME_ZONE in Django The default timezone is TIME_ZONE = 'UTC' . TIME_ZONE = 'Asia/Calcutta' . For applying these changes we need to set the USE_TZ variable to TRUE.

How do I get local timezone in Python?

Use the datetime. now() method to get the current time. Use the timezone class with UTC instance with a now() method to to get the current UTC time in Python.


1 Answers

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())
like image 196
supervacuo Avatar answered Oct 13 '22 11:10

supervacuo