Filter DateTimeField Models with Date format in Django


When we have DateTimeField, sometimes we have a need to filter it by Date. For example, given a models called “Insurance” :

1
2
3
class Insurance(models.Model):
    name = models.CharField(max_length=255)
    created = models.DateTimeField()

Given data :

1
2
3
4
5
6
7
8
===================================
| Name     |  Created             |
===================================
| Yodi     | 2012-01-03 03:01:01  |
| Toms     | 2012-01-03 03:34:21  |          
| Mandy    | 2012-01-04 04:08:41  |          
| Tara     | 2012-01-05 05:24:11  |          
……..


We want to get all clients in 2012-01-03, which should be “Yodi” and “Toms”.
So you can do with this querySet :

1
2
3
4
5
6
7
8
9
import datetime

date_string = ‘2012-01-03’
value = datetime.datetime.strptime(‘2012-01-03’, ‘%Y-%m-%d’)

queryset = Insurance.objects.filter(created__range=(
                        datetime.datetime.combine(value, datetime.time.min),
                        datetime.datetime.combine(value, datetime.time.max))
                        )

This will query all record with range : 2012-01-03 00:00:00 until 2012-01-03 23:59:59.

How if we want to search between two date ?
It’s easy, just doing this querySet :

1
2
3
4
5
6
7
8
9
10
11
import datetime

start_date_string = ‘2012-01-02’
end_date_string = ‘2012-01-20’

start = datetime.datetime.strptime(start_date_string, "%Y-%m-%d")
end = datetime.datetime.strptime(end_date_string, "%Y-%m-%d")
daterange = [datetime.datetime.combine(start, datetime.time.min),
                         datetime.datetime.combine(end, datetime.time.max)]

queryset = Insurance.objects.filter(created__range=daterange)

So, there no problem for searching Date in DateTimeField.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.