问题
I undrestand that this question is repeated, but unfortunately I cannot find any answer.
My impression is that Django already takes care of converting server time to local user as long as I have
TIME_ZONE = 'UTC'
USE_TZ = True
in my settings.
Even more if the db is postgresql that setting also doesn't matter and every thing will be still converted.
however I tried all the followings:
{% load tz %}
{{ obj.date }}
{{ obj.date|localtime }}
{{ obj.date | timezone:"Canada/Mountain" }}
and only last one works and the rest gives me UTC time. Last one also is not useful as the time would be only correct for users in that zone.
I was wondering if I am missing anything here.
I have a very simple test model:
class TimeObject(models.Model):
date = models.DateTimeField(auto_now=True)
回答1:
My impression is that Django already takes care of converting server time to local
Unfortunately that is incorrect.
As discussed here, there's no automatic way of knowing what the user's timezone is. You need to figure that out in some other way (it could be saved as a user setting, for example). Then you need to activate() that timezone. Once you do, Django will perform the conversion.
来源:https://stackoverflow.com/questions/65174060/how-to-convert-utc-time-to-users-local-time-in-django