How to display the current year in a Django template?

PythonDjango

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

Solution 3 - Python

Solution 4 - Python

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

Solution 5 - Python

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWilly NelsonView Question on Stackoverflow
Solution 1 - PythonHaldean BrownView Answer on Stackoverflow
Solution 2 - PythoncabhishekView Answer on Stackoverflow
Solution 3 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 4 - PythonhygullView Answer on Stackoverflow
Solution 5 - PythonCloud ArtisansView Answer on Stackoverflow