【问题标题】:query is getting UTC timestamp from the database but local time is stored in the database查询正在从数据库中获取 UTC 时间戳,但本地时间存储在数据库中
【发布时间】:2019-02-01 06:57:55
【问题描述】:

由于某种原因,我的查询集返回 UTC 时间,但是在数据库中,它应该获取的时间是本地时间。有谁知道为什么会这样?感谢您的帮助

last_checkin_time 方法是从数据库中获取用户最后一次签入时间戳的方法,现在我只需将它发布到我的切换方法中的 time_delta 变量中,这样我就可以看到它得到了什么值。 (一旦我得到这个时区,就会发现 time_delta 将是一个实际的时间增量)

这是我的模特经理

class UserActivityManager(models.Manager):

    def current(self, user):
        current_obj = self.get_queryset().filter(user=user).order_by('-timestamp').first()
        return current_obj

    def last_checkin_time(self, user):
        last_activity_time = self.get_queryset().order_by('-timestamp').filter(user=user, activity="checkin").first()
        return last_activity_time

    def toggle(self, user):
        last_item = self.current(user)
        activity = "checkin"
        time_delta = None
        last_checkin = self.last_checkin_time(user)
        if last_item is not None:
            if last_item.timestamp <= tz.localize(datetime.datetime.now()):
                pass
            if last_item.activity == "checkin":
                activity = "checkout"
                time_delta = last_checkin.timestamp

        obj = self.model(
                user=user,
                activity=activity,
                time_delta = time_delta,
        )
        obj.save()
        return obj

这是我数据库中的表的样子(关注最后几行中的 time_delta 字段)

编辑:

另外我应该提到我的模型中的时间戳字段设置为 auto_now_add=True 即。 时间戳 = models.DateTimeField(auto_now_add=True)

不确定是不是这个问题

【问题讨论】:

  • 我不认为 DB 可以节省本地时间。我认为 DB 客户端(屏幕截图中的表格) 在您的本地时间显示它
  • 所以我可能需要在从数据库中获取时区后的某个时间设置它?这也是我的想法,但是当我尝试使用 tz.localize(last_checkin.timestamp) 作为值时,我收到错误“Not naive datetime (tzinfo is already set)”

标签: django django-models


【解决方案1】:

我需要使用 tz.normalize(last_checkin.timestamp),而不是使用 tz.localize(last_checkin.timestamp)。似乎由于时间戳已经设置为 UTC,我需要使用 normalize 方法更改它,而不是 localize

【讨论】:

    猜你喜欢
    • 2020-10-10
    • 2014-01-28
    • 2015-03-19
    • 2011-04-17
    • 2016-08-24
    • 2021-05-19
    • 2017-02-02
    • 2011-01-16
    • 1970-01-01
    相关资源
    最近更新 更多