[Fixed]-Django filter by datetime on a range of dates

28👍

You can use range lookup. Just find the lowest and greater date and then apply it as:

queryset.filter(created_at__range=(start_date, end_date))

12👍

You can use range e.g.

import datetime

first_date = datetime.date(2005, 1, 1)
last_date = datetime.date(2005, 3, 31)
queryset.filter(created_at__range=(first_date, last_date))
👤JamesO

11👍

You can use __gte (greater than or equal) and __lte (less than or equal). For example:

queryset.filter(created_at__gte=datetime.date.today())

3👍

You can combine date and range field lookups:

queryset.filter(created_at__date__range=(start_date, end_date))

1👍

queryset.filter(created_at__range=(start_date, end_date)) this will lead to problem which is the end date will be exlusive let take example how will the sql will look to this query as created_at >= "start_date 00:00:00" AND created_at <= "end_date 00:00:00" so the best solution is to add max time in date to the end date which is "23:59:59" so it will created_at >= "start_date 00:00:00" AND created_at <= "end_date 23:59:59"so you can a achieve this by doing

import datetime
queryset.filter(created_at__range=(
    datetime.datetime.combine(start_date, datetime.time.min),
    datetime.datetime.combine(end_date, datetime.time.max),
))

also if adding 1 to end date this will be wrong approach because the end date will be end_date+1 00:00:00 so the query will include also the end_date+1 00:00:00 which is wrong

there is another answer for this we can change the datetimefield to datefield

queryset.annotate(Date = Cast('created_at', DateField())).filter(Date__range=(start_date,end_date))

and there is another answers you play around with it like

queryset.filter(Q(created_at__range=(start_date,end_date)) | Q(created_at__icontains=end_date) )

OR

queryset.filter(Q(created_at__range=(start_date,end_date)) | Q(created_at__startswith=end_date) )

-3👍

Leave a comment