Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two dates in Jinja2?

Tags:

python

jinja2

Is there a specific way of comparing two dates in Jinja?

I have googled and searched but have found close to nothing related to this specific question.

The closest thing I have found is this, from the official Jinja2 documentation:

It is also possible to sort by an attribute (for example to sort by the date of an object) by specifying the attribute parameter:

{% for item in iterable|sort(attribute='date') %}
    ...
{% endfor %}
like image 727
Xar Avatar asked Nov 03 '14 16:11

Xar


1 Answers

I'm not sure what you are looking for but this is how you can compare a datetime to datetime.now().

I have found that a datetime object can create a new datetime object:

In [1]: import datetime

In [2]: wasNow = datetime.datetime.now()

In [3]: wasNow
Out[3]: datetime.datetime(2017, 7, 28, 14, 17, 21, 889530)

In [4]: wasNow.now()
Out[4]: datetime.datetime(2017, 7, 28, 14, 17, 30, 105077)

and now that you have a date object in the jinja template you are able to create a new datetime object from an existing one and compare it like:

{% if item.date < item.date.now() %}
  <p> This will display if the item.date is before item.date.now(). </p>
{% endif %}

I hope that this helps you some in trying to compare dates using jinja.

like image 164
Brandon G Avatar answered Oct 21 '22 09:10

Brandon G