Comparing dates in template Django
<p>I have two dates in a template that I need to compare in an if statement.</p>

<p>Date1 is from the created field of a data element {{ endjob.created|date:"Y-m-d" }} that is displayed as 2016-09-12</p>

<p>Date2 if from an array {{ pay_period.periods.0.0 }} that is displayed as 2016-09-04</p>

<p>Therefore I am trying to ask to display information only if Date1 >= Date2 but I do not get any data.</p>

<p>Can you help me with how to clash dates in templates in Django</p>

<p>This is my code:</p>

<pre><code>&lt;tbody&gt;     
{% for endjob in endjob %}
        {% if endjob.created|date:"Y-m-d" &gt;= pay_period.periods.0.0  %}
            &lt;tr&gt;
            &lt;td&gt;&lt;a href="{{ endjob.get_absolute_url }}" title="Goto Form"&gt;{{ endjob.event.name }}&lt;/a&gt;&lt;br /&gt;&lt;/td&gt;
            &lt;td&gt;{{ endjob.event.job_no}} &lt;br /&gt;&lt;/td&gt;
            &lt;td&gt;{{ endjob.event.job_type}} &lt;br /&gt;&lt;/td&gt;
            &lt;td&gt;{{ endjob.code }} &lt;br /&gt;&lt;/td&gt;
            &lt;td&gt;{{ endjob.crewid }}&lt;br /&gt;&lt;/td&gt;
            &lt;td&gt;{{ endjob.workers }}&lt;br /&gt;&lt;/td&gt;
            &lt;td&gt;{{ endjob.created|user_tz:user|date:"M j, Y" }}&lt;br /&gt;&lt;/td&gt;
            &lt;/tr&gt;
       {% endif %}
{% endfor %}
</code></pre>

<p></p>

<p>You are probably comparing two different data types which is why you are not getting anything. By doing <code>endjob.created|date:"Y-m-d"</code>,you are converting <code>endjob.created</code> to a string. Yes, <code>{{ pay_period.periods.0.0 }}</code> is displayed as the string '2016-09-04'. That is what the <code>{{ }}</code> thing does. However in the expression <code>endjob.created|date:"Y-m-d" &gt;= pay_period.periods.0.0</code>, you are comparing a string VS the original data type of <code>pay_period.periods.0.0</code>.</p>

<p>To solve this, just make sure the datatypes match upon comparison. You can probably get away with <code>endjob.created|date:"Y-m-d" &gt;= pay_period.periods.0.0|date:"Y-m-d"</code>, but I do not recommend it. Unless there is a very good reason you must do it this way, I suggest doing the comparison elsewhere other than on the template level, and then pass a boolean or call a boolean attribute instead like <a href="http://stackoverflow.com/a/3798865/4284628">so</a>.</p>

python django