Django Admin DateTimeField Showing 24hr format time
Asked Answered
G

3

9

I tried on google but I did not found the solution. In Django admin side, I'm displaying start date and end date with time. But time is in 24 hr format and I want to display it in 12 hr format

class CompanyEvent(models.Model):
    title = models.CharField(max_length=255)
    date_start = models.DateTimeField('Start Date')
    date_end = models.DateTimeField('End Date')
    notes = models.CharField(max_length=255)

    class Meta:
        verbose_name = u'Company Event'
        verbose_name_plural = u'Company Events'

    def __unicode__(self):
        return "%s (%s : %s)" % (self.title, self.date_start.strftime('%m/%d/%Y'), self.date_end)

I also found out this but it isn't helping me.

I am new to python and django. Please help.

Screen Shot

Gallego answered 30/1, 2018 at 5:6 Comment(1)
I think it captures the default from your computer. So if you region is in 24h format, it will show it like that. Have you tried changing your region format?Farica
L
18

This is a matter for django's settings, not the model: settings doc.

Check your TIME_INPUT_FORMATS in MyProject/MySite/settings.py and add this as necessary:

TIME_INPUT_FORMATS = [
    '%I:%M:%S %p',  # 6:22:44 PM
    '%I:%M %p',  # 6:22 PM
    '%I %p',  # 6 PM
    '%H:%M:%S',     # '14:30:59'
    '%H:%M:%S.%f',  # '14:30:59.000200'
    '%H:%M',        # '14:30'
]

If the display of the time format on the changelist page is still wrong, check your LANGUAGE_CODE and USE_L10N settings.

Leonilaleonine answered 9/2, 2018 at 9:57 Comment(0)
L
7

Take a look at Django docs you will get to know format like this

'%Y-%m-%d %H:%M:%S'

where %H is Hour, 24-hour format with leading zeros, to get 12-hour format replace it with %h

So you have to use- '%Y-%m-%d %h:%M:%S'

Lone answered 30/1, 2018 at 12:39 Comment(0)
C
3

Defaultly django displays 24 hrs format, if you want to customize you need to specify the 12 hrs format. Let me know if this works

class CompanyEvent(models.Model):
title = models.CharField(max_length=255)
date_start = models.DateTimeField('Start Date')
date_end = models.DateTimeField('End Date')
notes = models.CharField(max_length=255)

class Meta:
    verbose_name = u'Company Event'
    verbose_name_plural = u'Company Events'

def __unicode__(self):
    return "%s (%s : %s)" % (self.title, self.date_start.strftime('%m/%d/%Y %I:%M %p'), self.date_end)
Charnel answered 30/1, 2018 at 5:14 Comment(2)
It working fine for listing but not in detail or edit page.Gallego
Check the image i provided , that image is of edit view there i am getting the time format in 24 hr .Gallego

© 2022 - 2024 — McMap. All rights reserved.