'django filter by datetime on a range of dates

I have a model with field "created_at", and I have a list of dates. So, I want to get all the models that are created in the date range. How ?

I know that we can compare datetime and date easily using:

queryset.filter(created_at__startswith=date)

But, I have a range of dates, so how ?
Let me know for more information.



Solution 1:[1]

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))

Solution 2:[2]

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))

Solution 3:[3]

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

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

Solution 4:[4]

You can combine date and range field lookups:

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

Solution 5:[5]

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) )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aamir Rind
Solution 2 Seonghyeon Cho
Solution 3 Simeon Visser
Solution 4 Ali Shamakhi
Solution 5