How to display the current year in a Django template?

Question:

What is the inbuilt template tag to display the present year dynamically. Like “2011” what would be the template tag to display that?

Asked By: Willy Nelson

||

Answers:

The full tag to print just the current year is {% now "Y" %}. Note that the Y must be in quotes.

Answered By: Haldean Brown

{% now 'Y' %} is the correct syntax

Answered By: cabhishek

In my template, aside from the current year, I needed a credit card expiration year dropdown with 20 values (starting with the current year). The select values needed to be 2 digits and the display strings 4 digits. To avoid complex template code, I wrote this simple template tag:

@register.filter
def add_current_year(int_value, digits=4):
    if digits == 2:
        return '%02d' % (int_value + datetime.datetime.now().year - 2000)
    return '%d' % (int_value + datetime.datetime.now().year)

And used it in the following manner:

<select name="card_exp_year">
    {% for i in 'iiiiiiiiiiiiiiiiiiii' %}
    <option value="{{ forloop.counter0|add_current_year:2 }}">{{ forloop.counter0|add_current_year:4 }}</option>
    {% endfor %}
</select>
Answered By: Cloud Artisans

I have used the following in my Django based website

{% now 'Y' %}

You can visit & see it in the footer part where I have displayed the current year using the below code(CSS part is omitted so use your own).

<footer class="container-fluid" id="footer">
    <center>
        <p>
           &copy;
           {% now 'Y' %}, 
           PMT Boys hostel <br> 
           All rights reserved
        </p>
    </center>
</footer>

And it is displaying the following centred text in my website’s footer.

©2018, PMT Boys hostel 
All rights reserved
Answered By: hygull
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.