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?
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.
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.
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.
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.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With