How to filter a DateTimeField by today's date in Django

Posted by Chris Bartos on March 7, 2016

Are you getting validation errors when you try to filter a DateTimeField by today’s date?

It can be a huge pain, when, you can’t for the life of you get Django to filter correctly on today’s date.

There is one, simple way of solving this problem.

Once you understand how to do this, you’ll laugh at how easy it was to implement.

Let’s say, for example, that you have a column in a model called post_date.

class MyModel(models.Model):
    post_date = models.DateTimeField(auto_add_now=True)
    # ... additional fields ...

How do you filter DateTimeField by today’s date?

The problem is that you have is that you need today’s posts, but it’s tough because, you’re model is implemented as a DateTimeField. You need to match the actual date. In order to do that you need to match the year, month and day explicitly.

from datetime import date
today = date.today()
today_filter =  MyModel.filter(post_date__year=today.year,
                               post_date__month=today.month,
                               post_date__day=today.day)

But that’s too much typing!

You might think this is way to much to type every time you want want to filter records by date. Are there some things that you can do to make this easier?

Sure! You can create a helper function.

def filter_by_date(date):
    return MyModel.filter(post_date__year=date.year,
                          post_date__month=date.month,
                          post_date__day=date.day)

Or, you can upgrade your instance of Django to 1.9 where there is a filter specifically for dates.

from datetime import date
MyModel.filter(post_date__date=date.today())

The choice is yours! But, now you know exactly what you need to do to filter by date.

Similar Posts

What do you do when 'makemigrations' is telling you About your Lack of Default Value
How to Implement Many-To-Many Relationship in Django
Test your Queries before they make it into Production using the Django Shell
I have a ChoiceField Callable that Includes a Queryset but it Breaks my Django app
Help! My Models feel Bloated! Why you should write a custom Manager


What do you do after the Official Django Tutorial?

Here's what you'll learn:

  1. Start writing tests
  2. Increase the size / complexity of the Polls application.
  3. Learn how to code in Django by reading the Django source code.
  4. Finding code snippets to use in your website by reading the code of other websites.
  5. Using Javascript in a web app.
  6. Deploying on Heroku and AWS.
We won't send you spam. Unsubscribe at any time. Powered by ConvertKit


Get some value from this post? Please like and share this post because more people also deserve some value. :-)