how to change the datetime format in admin panel?

I have an answer model with str method as defined below:

class Answer(models.Model):
    created_at = models.DateTimeField(auto_now_add=True, null=True)

    def __str__(self):
        return  "(" + str(self.created_at)  + ")"

I would like to show in this format Feb. 27, 2021, 6:55 p.m in the admin panel

but it shows like this in admin panel

enter image description here

How can i achieve the above format? Thanks for the help!


So it turns out this can be done without any external libraries like pytz.

here is the solution i went with.

from django.utils import timezone

In the str method of the model

def __str__(self):
    return  "(" + timezone.localtime(self.created_at).strftime('%b %d, %Y, %I:%M %p')  + ")"


DateTimeField holds a datetime.datetime object.

You can convert that object by using the object’s strftime method. An official reference is here:

In your case, try

created_at_str = created_at.strftime('%b %d, %y, %I:%M %p')

Leave a Reply

Your email address will not be published. Required fields are marked *