Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django how to use DateTimeField without microseconds?

My field in model:

created_at = models.DateTimeField(auto_now_add=True)

it returns: "created_at": "2023-02-21T09:24:55.814000Z"

how can i get this one (without last part): "created_at": "2023-02-21T09:24:55"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there another way instead of this?
(part from the django rest framework serializer)

representation['created_at'] = instance.created_at.split('.')[0]

>Solution :

You can use strftime method to format the datetime in the way you want:

created_at.strftime("%Y-%m-%dT%H:%M:%S")
# Should give "2023-02-21T09:24:55"

Generically in your APIs, ISO-8601 format should be preferred. You can use created_at.isoformat() to get the string representation in that format.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading