How to Convert UTC Time To User's Local Time in Django

白昼怎懂夜的黑 提交于 2021-02-08 09:00:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!