How to compare dates in Django templates

I would like to compare a date to the current date in Django, preferably in the template, but it is also possible to do before rendering the template. If the date has already passed, I want to say "In the past" while if it is in the future, I want to give the date.

I was hoping one could do something like this:

{% if listing.date <= now %} 
     In the past 
{% else %} 
     {{ listing.date|date:"d M Y" }} 
{% endif %}

With now being today's date, but this does not work. I couldn't find anything about this in the Django docs. Can anyone give some advice?


Compare date in the view, and pass something like in_the_past (boolean) to the extra_context.

Or better add it to the model as a property.

from datetime import date

@property
def is_past_due(self):
    return date.today() > self.date

Then in the template:

{% if listing.is_past_due %}
    In the past
{% else %}
    {{ listing.date|date:"d M Y" }}
{% endif %}

Basically the template is not the place for date comparison IMO.


As of Django 1.8 the following slightly distasteful construct does the job:

{% now "Y-m-d" as todays_date %}
{% if todays_date < someday|date:"Y-m-d" %}
   <h1>It's not too late!</h1>
{% endif %}

Hackish, but it avoids the need for a custom tag or context processor.


I added date_now to my list of context processors.

So in the template there's a variable called "date_now" which is just datetime.datetime.now()

Make a context processor called date_now in the file context_processors.py

import datetime

def date_now(request):
    return {'date_now':datetime.datetime.now()}

And in settings.py, modify CONTEXT_PROCESSORS to include it, in my case it's

app_name.context_processors.date_now

addition to @bx2 beneficial answer, if your field is a datetime field just call date() function to models datetimefield:

from datetime import date

@property
def is_past_due(self):
    if date.today() > self.date.date():
        return True
    return False

EDIT: i think this could be shrunken to:

from datetime import date

@property
def is_past_due(self):
    return date.today() > self.date.date()