Explain Codes LogoExplain Codes Logo

How can I filter a date of a DateTimeField in Django?

python
django-orm
date-filtering
datetime
Alex KataevbyAlex Kataev·Feb 10, 2025
TLDR

To filter by date in Django, append __date to your DateTimeField in the .filter() method. Considering Event as a model with a event_date field, to get events on the 14th of March, 2023:

from datetime import date from myapp.models import Event # Hope you didn't forget PI day! events_on_spacific_date = Event.objects.filter(event_date__date=date(2023, 3, 14))

This yields all Event objects whose event_date falls on March 14, 2023.

Demystifying date-based filtering

Let's unravel the secrets behind date-based filtering in Django and tap into ORM capabilities.

Range-based date filtering

To get Event objects within a time window, make use of __gte (greater than or equal to) and __lt (less than):

from datetime import datetime # Don't remember the Ides of March, let March 15 live in peace events_within_date_range = Event.objects.filter( event_date__gte=datetime.combine(date(2023, 3, 14), datetime.min.time()), event_date__lt=datetime.combine(date(2023, 3, 15), datetime.min.time()) )

This retrieves events beginning on the 14th and ending before the 15th of March, 2023. The use of datetime.combine with datetime.min.time() includes all conceivable times during the day.

Year, month, or day-based filtering

Filtering by a specific year, month, or day is conveniently done with __year, __month and __day lookups:

# March, because March is the only month that burns. events_in_march = Event.objects.filter(event_date__month=3)

Time zone aware filtering

Time zones could impact your filtering. When filtering by date, datetime.now() over datetime.utcnow() or timezone.now() could give irrelevant results if time zone support is enabled in your Django settings.

Filtering events happening today

To filter the events running today, use date.today():

from datetime import date # Ah, an event-free day. Just like my social calendar. today_events = Event.objects.filter(event_date__date=date.today())

startswith and contains for date filtering

The __startswith and __contains lookups could provide quick filtering options that process the date as a string. But, beware, they may not give the calendar structure the reverence it deserves:

# Events in January, because who doesn't love the biting cold? events_in_january = Event.objects.filter(event_date__startswith='2023-01')

Using Django's date-based views

Django ships with some useful built-in views like django.views.generic.date_based, which helps to normalize the displaying of events happening today, this year, or any other custom relative date context.