Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I filter by time in a date time field?

Tags:

python

django

In the model 'entered' is a datetime field. I want to query the data to find all entry's that where made between noon(start_time) and 5:00pm (end_time).

selected = Entry.objects.filter(entered__gte=start_time, entered__lte=end_time)

(as I expected)I get an error of:

"ValidationError: Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format."

So I know I can use __year so I tried.

selected = Entry.objects.filter(entered__time__gte=start_time, entered__time__lte=end_time)

I get an error of:

"FieldError: Join on field 'start' not permitted. Did you misspell 'time' for the lookup type?"
like image 775
Steven H. Avatar asked May 27 '09 21:05

Steven H.


1 Answers

I don't believe there's built-in support for this, but you can pass extra where-clause parameters (warning: some possibility of introducing DB-dependent behaviour here).

For example, on Postgres, something like:

Entry.objects.extra(where=['EXTRACT(hour from entered) >= 12 and '\
                    'EXTRACT(hour from entered) < 17'])

If you're using potentially unsafe input to determine the values 12 and 17, note that you can also specify a params option to extra that will ensure proper quoting and escaping, and then use the standard sql %s placeholders in your where statement.

like image 126
Jarret Hardie Avatar answered Sep 22 '22 22:09

Jarret Hardie