How to compare two dates in Jinja2?

Is there a specific way to compare two dates in Jinja?

I searched Google and searched, but found almost nothing related to this particular issue.

The closest I found is 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 %}
+4
source share
1 answer

I'm not sure what you are looking for, but you can compare datetime with datetime.now ().

I 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 the date object in the jinja template, you can create a new datetime object from the existing one and compare it as:

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

I hope this helps you try comparing dates using jinja.

+1
source

All Articles