Django: datetime filter by date ignoring time

If you can't use the __date filter, I think the cleanest way would be to do this:

from datetime import datetime, timedelta

d = datetime.now()  # or whatever you want

match_queryset.filter(start__gte=d.date(), start__lt=d.date()+timedelta(days=1))

If you have USE_TZ=True in Django's settings.py, you will get warnings:

RuntimeWarning: DateTimeField (...) received a naive datetime (...) while time zone support is active.

but the filter will still work. The comparison will be made in Django's timezone (TIME_ZONE from settings.py), at least that's what I'm getting.


From Django 1.9 you can use the __date field lookup, exactly as you have mentioned in your question. For older versions, you will have to do with the other methods.

e.g.

Entry.objects.filter(start__date=datetime.date(2005, 1, 1))
Entry.objects.filter(start__date__gt=datetime.date(2005, 1, 1))

Tags:

Python

Django