2

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?

Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237
rayashi
  • 1,721
  • 3
  • 20
  • 28
  • possible duplicate of [Django query datetime for objects older than 5 hours](http://stackoverflow.com/questions/10345147/django-query-datetime-for-objects-older-than-5-hours) – Brandon Taylor Oct 09 '14 at 00:09
  • Not duplicate, I want to filter just by hour without month, year or day. – rayashi Oct 09 '14 at 11:11
  • It's the same principle. You need to filter your queryset using a timedelta, which you can extrapolate from the answer referenced. – Brandon Taylor Oct 09 '14 at 11:27
  • Its diferent. I want filter just hour lookup. Not full date with year, month, day. When I use "inicio__hour__gte" it retrun "FieldError Unsupported lookup 'hour' for DateTimeField or join on the field not permitted." – rayashi Oct 09 '14 at 19:12
  • If you know . Please answer the question with some code exemple. – rayashi Oct 09 '14 at 19:14

2 Answers2

8

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)
Adam Starrh
  • 6,428
  • 8
  • 50
  • 89
  • 2
    Beware. According to [docs](https://docs.djangoproject.com/en/2.2/ref/models/querysets/#hour): "When USE_TZ is True, datetime fields are converted to the **current time zone** before filtering. This requires time zone definitions in the database." – Augusto Destrero Mar 26 '21 at 14:42
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.

Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144