Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change django datetime format output?

I have a datetime object. This is my template file:

<ul>
<li>{{ sale.validity }}</li>
</ul>

and the output i'm getting is in the format:

July 18, 2012, midnight

I would really like to change the output to be numerical in the format: day-month-year so for example the above would be changed to:

18-07-2012

Can someone point me out to the right direction on this?

like image 695
Tom Avatar asked Jul 20 '12 11:07

Tom


People also ask

What is the format of datetime in Django?

DATETIME_FORMAT="%Y-%m-%d%H:%M:%S"

How do I change the date and time in Django?

The simplest approach to define or retrieve the date in Django is to use python's DateTime module. This datetime module contains many different classes that can be used to manipulate date values. To generate or fetch dates, we use the date class.

How do I change the default date in Django?

If you want to be able to modify this field, set the following instead of auto_now_add=True : For DateField : default=date.today - from datetime.date.today() For DateTimeField : default=timezone.now - from django.utils.timezone.now()

How do I change the date format in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.


1 Answers

Per Django docs, you can use a date filter to format date:

{{ sale.validity|date:"d-m-Y"}} 

Additionally, you can also set DATE_FORMAT (or DATETIME_FORMAT) setting to set a project-wide default for displaying such values if USE_L10N is False. If it's true, you'll want to have a look at this documentation on format localization.

like image 181
Jonas Geiregat Avatar answered Oct 10 '22 19:10

Jonas Geiregat