3

I'm trying to change DateTime format for all date time objects in my project. I want to format :

    21-06-2021 14:02:12

My settings

DATETIME_FORMAT = '%d-%m-%Y %H:%M:%S'
TIME_ZONE = 'Africa/Tunis'
USE_I18N = True
USE_L10N = False  
USE_TZ = True 

Result:

%21-%06-%2021 %14:%Jun:%st
  • 1
    `DATETIME_FORMAT` does not use Python's datetime module syntax, have a look at the [documentation](https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#std:templatefilter-date) on what types of format strings are acceptable. – Abdul Aziz Barkat Jun 21 '21 at 13:15

1 Answers1

2

The DATETIME_FORMAT setting [Django-doc] works with the formatting specifications like PHP does that.

So as format, you should use:

DATETIME_FORMAT = 'd-m-Y H:i:s'

Note that the formatting is slightly different [PHP datetime specs]. PHP uses i for the minutes; and a lowercase s for the seconds:

format character Description Example
i Minutes with leading zeros 00 to 59
s Seconds with leading zeros 00 through 59

The Django documentation also has the format characters listed as @AbdulAzizBarkat says.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • 2
    This link would be better for a comprehensive list than the PHP one: https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#std:templatefilter-date :) Since the documentation states: "Uses a similar format to PHP’s `date()` function with some differences" – Abdul Aziz Barkat Jun 21 '21 at 13:19
  • Thank you both for your help. I checked the django documentation and the available format strings. the new format is : DATETIME_FORMAT = '%d-%m-%Y %H:%i:%s'. it works. But i don't know why in my templates result be like : %21-%06-%2021 %14:%28:%18 with % . – Jihene Ben gamra Jun 21 '21 at 13:50
  • @JiheneBengamra: because it does not parses the `%` as a prefix for a variable but just a character to yield. It thus will generate a string with `%`, the day of the month (`d`), so `21`, etc. However Django, the `DateTimeFIeld `input_formats` use percentage formatting (https://docs.djangoproject.com/en/dev/ref/forms/fields/#datetimefield), so it uses two datetime formats, hence the confusion. – Willem Van Onsem Jun 21 '21 at 14:10