How do I change the 12 hour format in django?

70 Views Asked by At

I have a DateTimeField in my model.

When I add this field to admin.py , then the format shows as 4:00 pm , how can this be changed to 16:00?

creation_date = models.DateTimeField(auto_now_add=True,)

If I do this

def time(self):
return self.creation_date.timezone().strftime('%Y-%m-%d %H:%M:%S')

that time field is not sorted

2

There are 2 best solutions below

0
On BEST ANSWER

You can override the format with the DATETIME_FORMAT setting: https://docs.djangoproject.com/en/4.2/ref/settings/#datetime-format

Default: 'N j, Y, P' (e.g. Feb. 4, 2003, 4 p.m.)

The default formatting to use for displaying datetime fields in any part of the system. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead. See allowed date format strings.

0
On

You can change the time format in Django admin by creating a custom admin model and overriding the date_hierarchy attribute. Here's how you can do it:

from django.contrib import admin
from .models import YourModel

@admin.register(YourModel)
class YourModelAdmin(admin.ModelAdmin):
    date_hierarchy = 'creation_date'
    date_hierarchy_drilldown = False

    def changelist_view(self, request, extra_context=None):
        self.date_hierarchy = request.GET.get('dh', 'creation_date')
        return super().changelist_view(request, extra_context=extra_context)

In this code, YourModel should be replaced with the name of your model. This will change the date format in the Django admin interface to a 24-hour format.

As for the sorting issue, Django admin should automatically sort the DateTimeField in descending order. If it's not sorting correctly, you might want to check if there's any custom sorting applied in your admin model.

If you want to sort by the creation_date field, you can add it to the ordering attribute in your admin model:

class YourModelAdmin(admin.ModelAdmin):
    ordering = ('-creation_date',)

This will sort your model instances by creation_date in descending order in the Django admin interface.