[Fixed]-Django filter datetime base on date only

51👍

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)

Leave a comment