Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin DateTimeField Showing 24hr format time

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

like image 550
Amitesh Kumar Avatar asked Jan 30 '18 05:01

Amitesh Kumar


People also ask

What is the format of DateTimeField in Django?

DateTimeField in Django Forms is a date field, for taking input of date and time from user. The default widget for this input is DateTimeInput. It Normalizes to: A Python datetime. datetime object.


3 Answers

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.

like image 183
CoffeeBasedLifeform Avatar answered Sep 19 '22 06:09

CoffeeBasedLifeform


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'

like image 23
Sam Avatar answered Sep 22 '22 06:09

Sam


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)
like image 41
Sakthi Panneerselvam Avatar answered Sep 18 '22 06:09

Sakthi Panneerselvam