如何在Django中将UTC时间转换为用户的本地时间 [英] How to Convert UTC Time To User's Local Time in Django

查看:28
本文介绍了如何在Django中将UTC时间转换为用户的本地时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不理解这个问题是重复出现的,但是不幸的是我找不到任何答案.

I undrestand that this question is repeated, but unfortunately I cannot find any answer.

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

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

在我的设置中.

如果数据库是 postgresql ,该设置也无关紧要,每件事仍然会转换.

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" }}

,只有最后一个有效,其余的给了我UTC时间.最后一个也是没有用的,因为时间只适合该区域中的用户.

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)

推荐答案

我的印象是Django已经负责将服务器时间转换为本地时间

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

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

Unfortunately that is incorrect.

如在此处,无法自动了解用户的时区.您需要以其他方式弄清楚(例如,可以将其保存为用户设置).然后,您需要 activate() 该时区.完成后,Django将执行转换.

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.

这篇关于如何在Django中将UTC时间转换为用户的本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆