如何在 Django 中将 UTC 时间转换为用户本地时间

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

我不明白这个问题被重复了,但不幸的是我找不到任何答案。

我的印象是 Django 已经负责将服务器时间转换为本地用户,只要我有

TIME_ZONE = 'UTC'
USE_TZ = True

在我的设置中。

如果 db 是 postgresql,则设置也无关紧要,所有内容仍将被转换。

但是我尝试了以下所有方法:

{% load tz %}
{{ obj.date }}
{{ obj.date|localtime }}
{{ obj.date | timezone:"Canada/Mountain" }}

只有最后一个有效,其余的给我 UTC 时间。最后一个也没有用,因为时间只对那个区域的用户是正确的。

我想知道我是否遗漏了什么。

我有一个非常简单的测试模型:

class TimeObject(models.Model):
    date = models.DateTimeField(auto_now=True)

My impression is that Django already takes care of converting server time to local

不幸的是,这是不正确的。

正如所讨论的 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() 那个时区。完成后,Django 将执行转换。