I'm developing a Django app I have a model in which timestamps is added automatically. I want to show the time to the end users according to their local timezone.
Here is my code:
settings.py
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
model.py
date_created = models.DateTimeField(auto_now_add=True, null=True)
template
{{object.date_created}}
But it is showing UTC time I want this to detect user's current timezone and render date&time accordingly.
CodePudding user response:
The Django framework provides a built-in way to show local time to the user. When Django renders a template, it automatically passes in a variable called {{ localtime }} . This variable contains the current local time in the user's time zone.
If you want to display the local time in a specific format, you can use the Django template filter |date:"FORMAT" . For example, to display the local time in the "long" format, you would use the following code:
{{ localtime|date:"l, F jS Y H:i" }}
This would output something like "Sunday, January 1st 2017 12:00".
CodePudding user response:
Your data is stored in UTC which is good. When you obtain a DateTime field object from the database it will be a naive datetime.datetime object. ie A date/time without a timezone attached. It's then up to you to do the conversion.
User of your webapp may be in different time zones so the conversion to an appropriate time zone must occur for each request. This is why there is an activate function to set the current time zone.
If you have pytz installed you should be able to do the following:
from django.utils.timezone import activate
activate(settings.TIME_ZONE)
All output of date field in the template engine will then automatically convert you naive date time objects to the correct time zone for display.
If you just have a single naive datetime.datetime instance that you want to set the time zone on, then just use the pytz module directly. It is not normal to do this in your views though, as it's a good idea to only convert the time zone at the point of presentation.
from pytz import timezone
settings_time_zone = timezone(settings.TIME_ZONE)
last_updated = last_updated.astimezone(settings_time_zone)