inmate37
inmate37

Reputation: 1238

How to filter by range of specific hours in Django Orm?

I have a queryset below, that allows me to get objects that where created at last 14 days:

qs_1 = Model.objects.filter(datetime_created__gte=datetime.now()-timedelta(days=14))

What I want is to create a new queryset that will allow me to get objects for last 14 days and filter them by range from 11 pm to 9am. How can I do that ?

Upvotes: 1

Views: 2456

Answers (1)

hynekcer
hynekcer

Reputation: 15548

Read examples about hour lookup.

... Takes an integer between 0 and 23.

I think that the most readable solution is:

from django.db.models import Q
MyModel.objects.filter(Q(datetime_created__hour__lt=9) |
                       Q(datetime_created__hour__gte=23))

An lt lookup is because you probably definitely don't want 09:00:01am or 09:59:59am and don't need 09:00:00am. The time lookup can be used in more complicated cases if minutes are important. A "filter" by .exclude(...__hour__between=(8, 22)) is not a clear solution that could select also null timestamps and could have non trivial consequences like left joins etc. It requires to think longer than to read twice datetime_created__hour....

Upvotes: 4

Related Questions