0

Im using the auto_now_add field for DateTimeField in django and I'm displaying a date like this 2019-05-08T09:23:09.424129Z and I want to convert it to this format {YYYY-MM-DD} {HH:MM AM/PM} without changing the model since we are in production.

Most of the examples I found on the web require you to add something in the model any workarounds?

Model:

created = models.DateTimeField(auto_now_add=True, null=True)
funie200
  • 3,688
  • 5
  • 21
  • 34
user799451
  • 81
  • 12
  • 1
    Where do you want to display your date ? In the admin, in a template ? – Benbb96 May 09 '19 at 09:38
  • 2
    Yeah, same question, it depends on what you want to achieve. I believe you may find [this answer useful](https://stackoverflow.com/questions/7737146/how-to-change-the-default-django-date-template-format) if it's only about displaying date and datetime in your view/template/page. – Exirel May 09 '19 at 09:58

1 Answers1

2

If you want to display it on a template, you should use the date filter :

{{ instance.created|date:"Y-m-d h:i A" }}

Or in Python, you can use the strftime function :

print(instance.created.strftime("%Y-%m-%d %I:%M %p"))
Benbb96
  • 1,973
  • 1
  • 12
  • 21