从现在开始的一小时,正确地Django查询数据/对象的日期时间

时间:2019-05-28 07:10:50

标签: python django django-rest-framework

我正在过滤Django查询,以获取从现在起的最后一小时的更新时间,该模型具有DateTimeField。

这是为了获取一小时前更新的所有更新时间,我尝试使用datetime.now()-timedelta(hours = 1),并使用range(min,max)

我正在使用的

视图(generics.ListAPIView):

模型

updatetime = models.DateTimeField(blank=True, null=True)

onehours = datetime.now() - timedelta(hours=1) queryset = TbDevice.objects.filter(updatetime__gte=onehours).order_by('-updatetime')

此代码应返回上一小时前的更新时间,例如,下午2点应仅返回前一小时,但实际上显示了当天的所有数据

我通过手动更改值updatetime进行检查,只有最近时间14:57:00才显示大于06:48:00的数据

两者都有影响吗? 不同类型 Update time in my DB in Postman

using timezone Using timezone form django.utils the result is with my current time

1 个答案:

答案 0 :(得分:0)

哥!!

您在Indonesia(GMT + 7)中。您的数据库(使用系统时区)和django(使用UTC时区)相差7个小时。

使用时区识别日期时间格式尝试查询。

from django.utils import timezone
one_h_ago = timezone.now()-timezone.timedelta(hours=1)
queryset = TbDevice.object.filter(updatetime__gte=one_h_ago)

在邮递员中,您得到"updatetime": "2019-05-28T22:33:00+7:00" T 告诉我们您已启用时区支持。您已设置settings.USE_TZsettings.TIME_ZONE

希望这会有所帮助。如果您有任何问题,请告诉我。

很乐意提供帮助:)


这是您所了解的

从评论中我看到您的模型为:

class TbDevice(models.Model):
    nickname = models.CharField(max_length=32, blank=True, null=True) 
    email = models.CharField(max_length=64, blank=True, null=True) 
    status = models.CharField(max_length=64, blank=True, null=True) 
    createtime = models.DateTimeField(blank=True, null=True) 
    updatetime = models.DateTimeField(blank=True, null=True) 

    class Meta: 
        managed = False 
        db_table = 'device' 

对于createtimeupdatetime,您应该使用

createtime = models.DateTimeField(auto_now_add=True)
updatetime = models.DateTimeField(auto_now=True)

检查auto_nowauto_now_add以获得更多信息。