195

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

5 Answers 5

396

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

5
  • 6
    For the record, {% now %} won't give proper results for users within different time zone than the server. Jun 7, 2011 at 13:43
  • 32
    @Thomas True for some cases, however, the most common use case I've seen for wanting the current year is a copyright notice, and it's really not that important for it to be perfect for that 24 hours while Jan 1st makes its way around the world.
    – Endophage
    Sep 26, 2011 at 22:42
  • 2
    incidentally, that code is wrong, the Y must be quoted as in cabishek's answer.
    – Endophage
    Nov 3, 2011 at 19:41
  • If I was getting month i.e. "M" how would I get "Nov" to "November"
    – Josh
    Nov 16, 2017 at 13:06
  • 1
    @Josh the full docs are docs.djangoproject.com/en/dev/ref/templates/builtins/…, but you're looking for F instead of M Nov 28, 2017 at 20:03
53

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

16

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
15

{% now %}

1
0

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>
1
  • @mohammedqudah, depends on your needs! Dec 15, 2017 at 23:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.