【问题标题】:Lookup hour on DateTimeField DjangoDateTimeField Django 上的查找时间
【发布时间】:2014-12-03 18:25:31
【问题描述】:

我有模型

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

当我尝试进行此查询时:

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

它返回我:

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

如何进行此查询?

【问题讨论】:

  • 不重复,我想按小时过滤,没有月、年或日。
  • 原理是一样的。您需要使用 timedelta 过滤您的查询集,您可以从引用的答案中推断出来。
  • 不同。我想要过滤只是小时查找。不是带有年、月、日的完整日期。当我使用“inicio__hour__gte”时,它会重新运行“FieldError Unsupported lookup 'hour' for DateTimeField or join on the field not allowed。”
  • 如果你知道。请用一些代码示例回答问题。

标签: django django-models django-queryset


【解决方案1】:

请注意,这应该从 Django 1.9 开始工作

Event.objects.filter(timestamp__hour=23)
Event.objects.filter(time__hour=5)
Event.objects.filter(timestamp__hour__gte=12)

【讨论】:

  • 当心。根据docs:“当 USE_TZ 为 True 时,日期时间字段在过滤前转换为 当前时区。这需要在数据库中定义时区。”
【解决方案2】:

您需要使用 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 小时。

据我所知,根据documentation,您只能在小时、分钟或秒内进行精确查找。

【讨论】:

猜你喜欢
  • 2018-02-20
  • 2013-08-17
  • 2018-06-17
  • 2015-01-11
  • 2021-11-30
  • 1970-01-01
  • 2015-11-17
  • 2020-03-26
  • 2017-04-01
相关资源
最近更新 更多