【问题标题】:Record create and Update time not stored in localtime django记录创建和更新时间未存储在本地时间 django
【发布时间】:2018-02-20 19:32:39
【问题描述】:

我有一个模型“成员”,其中有两个字段“created_at”和“updated_at”。 最初,它们的定义如下:

created_at = models.DateTimeField(auto_now_add=True, null=True)
updated_at = models.DateTimeField(auto_now_add=True, null=True)

我的 settings.py 有 USE_TZ = True 和 TIME_ZONE = "America/New_York"。

我定义了一个自定义中间件来激活用户选择的时区。

current_tz = pytz.timezone("<user defined timezone>")
timezone.activate(current_tz)

然后,我更新字段以存储用户本地时间:

created_at = models.DateTimeField(default= lambda: timezone.localtime(timezone.now()), null=True)
updated_at = models.DateTimeField(default= lambda: timezone.localtime(timezone.now()), null=True)

现在,当我更新会员记录并检查 updated_at 时间时,它显示的是相同的 UTC 时区,而不是用户的本地时间。

是 django 总是以 UTC 格式将日期时间值存储在 DB 中还是我在这里遗漏了什么

【问题讨论】:

  • 这段代码只会使用服务器的本地时间,而不是用户。
  • 我已经编辑了我的问题,以提及根据用户选择的时区激活时区的中间件。那么,如何让它使用用户的本地时间而不是服务器呢?
  • 很公平。但这似乎仍然是个坏主意。为什么要存储本地时间,而不是像明确推荐的 in the docs 那样存储 UTC 并转换输出?
  • 因此,无需更新 created_at 和 updated_at 字段,只需在访问它们时将其值转换为本地时间。

标签: django timezone


【解决方案1】:

您的所有要求都应集中在USE_TZ = True

如果您设置USE_TZ = True,则 DateTimeField 存储 UTC 时间。 如果你在你的settings.py中评论USE_TZ = True,你就能得到你想要的。

但在项目中,最好始终打开USE_TZ,如果打开USE_TZ,所有的存储或内部处理甚至打印,都是UTC时区。当您在模板中显示时,time format conversion 非常方便。

【讨论】:

    猜你喜欢
    • 2012-11-30
    • 2011-03-30
    • 1970-01-01
    • 2021-05-27
    • 2018-11-04
    • 2020-10-10
    • 2023-03-15
    • 1970-01-01
    • 2017-08-31
    相关资源
    最近更新 更多