I have a model field time_stamp = models.DateTimeField(timezone.now)
. Now I want to search based on date range, like 2016-11-08 to 2016-12-08. How can I do that.

- 1,084
- 1
- 15
- 27
-
1Possible duplicate of [Django database query: How to filter objects by date range?](http://stackoverflow.com/questions/4668619/django-database-query-how-to-filter-objects-by-date-range) – AKS Dec 08 '16 at 06:20
-
date_range can be easily used in DateField but this is DateTimeField – Minuddin Ahmed Rana Dec 08 '16 at 06:41
-
Please check my answer. – AKS Dec 08 '16 at 06:47
4 Answers
From the documentation of range
lookup:
Filtering a
DateTimeField
with dates won’t include items on the last day, because the bounds are interpreted as “0am on the given date”.
Considering this, If you want items from the last date i.e. 2016-12-08
, you could consider using 2016-12-09
in the filtering.
import datetime
start_date = datetime.date(2016, 11, 8)
# use the day after 2016-12-08 to include it
end_date = datetime.date(2016, 12, 9)
Model.objects.filter(time_stamp__range=(start_date, end_date))
Or, use gte
and lte
lookups:
import datetime
start_date = datetime.date(2016, 11, 8)
end_date = datetime.date(2016, 12, 8)
Model.objects.filter(time_stamp__gte=start_date, time_stamp__lte=end_date))

- 18,983
- 3
- 43
- 54
https://docs.djangoproject.com/en/1.10/ref/models/querysets/#range
import datetime
start_date = datetime.date(2005, 1, 1)
end_date = datetime.date(2005, 3, 31)
Entry.objects.filter(pub_date__range=(start_date, end_date))

- 1
Model.objects.filter(time_stamp__range=["2016-11-08", "2016-12-08"])
Links Django database query: How to filter objects by date range?

- 1
- 1

- 137
- 1
- 5
If your django version is >= 1.9 you can use the date
casting on datetime field.
Model.objects.filter(time_stamp__date__gte=start_date, time_stamp__date__lte=end_date)
This will consider the timezone conversions also. Problem with other answers is that they are not considering that the filtering is being done on a datetime
field.
Django documentation on this: https://docs.djangoproject.com/en/1.9/ref/models/querysets/#date

- 2,314
- 1
- 18
- 21