Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django filter datetime base on date only

I'm trying to filter the query set in the BaseDatatableView on a date that's entered in by the user in the following format: mm/dd/yyyy. So start_date is in that format and will get converted to a datetime with strptime, see below.

I'd like to compare it to exactly a date datetimefield in the db, but i'd like to match the month, day, year exactly, disregarding the time. This is what I have so that doesn't work.

class AppointmentListJson(LoginRequiredMixin, BaseDatatableView):
             ....
    start_date = params.get('start_date', '')
    if start_date:  
        qs = qs.filter(start_date__contains=datetime.strptime(
            start_date, DATE_FORMAT))

    return qs

Thanks

like image 241
Joe Lones Avatar asked Feb 28 '14 03:02

Joe Lones


People also ask

How to filter datetime field in Django with date?

To filter a date of a DateTimeField in Python Django, we can use filter with a datetime. to call filter to return the results with the datetime_published field set to 2018-03-27.

How do I filter query objects by datetime range in Django?

To filter query objects by date range in Python Django, we can use the filter method. to call objects. filter with the date__range parameter set to a list with the date range with the strings as the date values. date is the column name we're filtering by.

What is Django Q?

Django Q is a native Django task queue, scheduler and worker application using Python multiprocessing.

What is filter Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.


Video Answer


1 Answers

Best Option (Django 1.9+ . - For datetime fields, casts the value as date. Allows chaining additional field lookups. Takes a date value.)

# Assumes the start_date variable is a datetime.date() instance or
# a value such as '2019-07-11'.
qs.filter(start_date__date=start_date)

# Note that you can also "chain" this result
qs.filter(start_date__date__lte=start_date)

Options for Django < 1.9

One option (break the date down in the filter):

start_date = datetime.strptime(start_date, DATE_FORMAT)
qs = qs.filter(
    start_date__year=start_date.year,
    start_date__month=start_date.month,
    start_date__day=start_date.day
)

Another option (set the min/max time for the date and use range):

from datetime import datetime
start_date = datetime.strptime(start_date, DATE_FORMAT)
start_date_range = (
    # The start_date with the minimum possible time
    datetime.combine(start_date, datetime.min.time()),
    # The start_date with the maximum possible time
    datetime.combine(start_date, datetime.max.time())
)
qs = qs.filter(start_date__range=start_date_range)
like image 162
Michael B Avatar answered Oct 17 '22 00:10

Michael B