Django Admin DateTimeField Showing 24hr format time

邮差的信 提交于 2019-12-08 17:17:09

问题


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.


回答1:


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.




回答2:


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'




回答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)


来源:https://stackoverflow.com/questions/48514222/django-admin-datetimefield-showing-24hr-format-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!