【问题标题】:django & postgres timezone localtime vs utcdjango 和 postgres 时区本地时间与 UTC
【发布时间】:2020-08-17 18:06:43
【问题描述】:

我将日期时间保存到我的 postgres 数据库中,然后在我的网站上显示它是错误的......

在我的models.py中:

datetime_start = models.DateTimeField()

在 postgres 中,时间是这样保存的:utc+2h:

在我的 django 中,我做了以下设置:

USE_TZ = True

TIME_ZONE = 'Europe/Paris'

在我的模板中,我得到了时间,为了测试,我显示了一次 UTC 和一次本地时间:

<th> Start </th>
<td>{{activity.datetime_start |utc|date:"d.m.Y H:i"}}</td>
<td>{{activity.datetime_start |localtime|date:"d.m.Y H:i"}}</td>

这里是我网站上的输出:

为什么这个输出是错误的? UTC时间应该是:06:00

本地时间应该是:08:00

我很困惑,我在时区和时间方面做错了什么? django 对 postgres 时间的解释是否错误?

【问题讨论】:

    标签: python django postgresql time


    【解决方案1】:

    我现在找到了解决方案。我在 postgres 中以错误的格式保存了时间。 因为我保存的时间已经是UTC时间了,所以我还要设置时区...

    data['value'] 对象已经是 UTC 时间,所以我添加了时区:

    import pytz
    
    start_datetime_tz = data['value'].replace(tzinfo=timezone.utc)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-23
      • 2020-07-26
      • 1970-01-01
      • 2012-09-23
      • 1970-01-01
      • 2020-11-14
      • 1970-01-01
      • 2014-10-05
      相关资源
      最近更新 更多