1

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.

Minuddin Ahmed Rana
  • 1,084
  • 1
  • 15
  • 27

4 Answers4

1

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))
AKS
  • 18,983
  • 3
  • 43
  • 54
0

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))
0
Model.objects.filter(time_stamp__range=["2016-11-08", "2016-12-08"])

Links Django database query: How to filter objects by date range?

Community
  • 1
  • 1
Dmitry Erohin
  • 137
  • 1
  • 5
0

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

Rag Sagar
  • 2,314
  • 1
  • 18
  • 21