How to format dateTime in django template?

DjangoDjango Models

Django Problem Overview


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)

Django Solutions


Solution 1 - Django

This is exactly what you want. Try this:

{{ wpis.entry.lastChangeDate|date:'Y-m-d H:i' }}

Solution 2 - Django

You can use this:

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

Solution 3 - Django

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?

Solution 4 - Django

{{ 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.

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
QuestionIProblemFactoryView Question on Stackoverflow
Solution 1 - DjangoRockystechView Answer on Stackoverflow
Solution 2 - DjangoCoc B.View Answer on Stackoverflow
Solution 3 - DjangorobView Answer on Stackoverflow
Solution 4 - DjangoRodrigo CamargosView Answer on Stackoverflow