How to format dateTime in django template?
Asked Answered
S

5

82

That:

{{ wpis.entry.lastChangeDate|date:"D d M Y" }}

gives me (why?):

2009-07-24 21:45:38.986156 

And, I don't know how to skip fraction part...

In my model, I have:

addedDate = models.DateTimeField(default=datetime.now)
Suspect answered 24/7, 2009 at 21:55 Comment(3)
Of course there is, here is all line <li>{{ wpis.entry.UserID.username }} @ [{{ wpis.entry.lastChangeDate|date:"D d M Y" }}]</li>Suspect
Strange, it works for me. Are you sure your lastChangeDate is Django DateTime?Broker
It is for addedDate not for lastChangeDate, that's why I am wondering.Broker
I
10

You can use this:

addedDate = datetime.now().replace(microsecond=0)

Irresolution answered 3/10, 2009 at 2:44 Comment(0)
R
235

This is exactly what you want. Try this:

{{ wpis.entry.lastChangeDate|date:'Y-m-d H:i' }}
Rochellerochemont answered 15/2, 2012 at 13:55 Comment(1)
Details on all available formatting options are Django docs: docs.djangoproject.com/en/dev/ref/templates/builtins/#dateVice
I
10

You can use this:

addedDate = datetime.now().replace(microsecond=0)

Irresolution answered 3/10, 2009 at 2:44 Comment(0)
E
5

I suspect wpis.entry.lastChangeDate has been somehow transformed into a string in the view, before arriving to the template.

In order to verify this hypothesis, you may just check in the view if it has some property/method that only strings have - like for instance wpis.entry.lastChangeDate.upper, and then see if the template crashes.

You could also create your own custom filter, and use it for debugging purposes, letting it inspect the object, and writing the results of the inspection on the page, or simply on the console. It would be able to inspect the object, and check if it is really a DateTimeField.

On an unrelated notice, why don't you use models.DateTimeField(auto_now_add=True) to set the datetime on creation?

Eyecup answered 24/7, 2009 at 22:51 Comment(0)
W
4

{{ wpis.entry.lastChangeDate|date:"SHORT_DATETIME_FORMAT" }}
Replace SHORT_DATETIME_FORMAT with the date and/or time format you desire to use.

Here's a list of available date and time formats to use in Django templates : https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#date https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#time

Make sure the filter is applied to the correct field.

Werby answered 7/12, 2020 at 12:54 Comment(1)
This also properly supports languages and localizations.Airfield
A
3

In addition to other answers, time filter below can only show a formatted time:

{{ wpis.entry.lastChangeDate|time:'H:i' }}
Alethaalethea answered 3/6, 2023 at 18:47 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.