Lookup hour on DateTimeField Django

跟風遠走 提交于 2020-01-17 04:39:05

问题


I have the model

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

When I try to make this query:

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

It returns me:

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

How can I make this query?


回答1:


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)

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.




回答2:


Heads up, this should work as of Django 1.9

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


来源:https://stackoverflow.com/questions/26267985/lookup-hour-on-datetimefield-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!