在DateTimeField Django上查找小时 [英] Lookup hour on DateTimeField Django

查看:189
本文介绍了在DateTimeField Django上查找小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有模型

class Item(models.Model):
    inicio = models.DateTimeField()

当我尝试进行此查询时:

When I try to make this query:

itens = Item.objects.filter(inicio__hour__gte=6)

它返回我:


FieldError不支持在DateTimeField中查找'小时'或不允许在字段上加入。

FieldError Unsupported lookup 'hour' for DateTimeField or join on the field not permitted.

如何进行此查询?

推荐答案

需要使用timedelta进行过滤:

You need to filter using a timedelta:

from datetime import datetime, timedelta

five_hours_ago = datetime.now() - timedelta(hours=5)
items = Item.objects.filter(inicio__lt=five_hours_ago)

您可以随时指定一个确切的日期时间,然后从当前日期时间起不到5个小时后减去5个小时。

You can always specify an exact datetime and then subtract 5 hours from it if you don't want 5 hours from the current datetime.

我的知识,和根据文档,您只能进行确切的查找一小时,分钟或秒。

To the best of my knowledge, and according to the documentation, you can only do an exact lookup on an hour, minute or second.

这篇关于在DateTimeField Django上查找小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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