[Django]-How to get a formatted DateTimeField value outside a Django template?

1👍

there may be a few different answers and each one will have it’s pros and cons.

I’m coming from the API world, where I can have multiple consumers of the API functions.

in your case you have a backend service which is returning structural data (json), in such a case it is goo do pass data, that will be independent of the consumer.

JSON does not have any standard format for the date, but there is ISO-8601, it is both human readable and structurized and easily parsable on the javascript side e.g. agular.js is parsing it without any additional efforts, moment.js (which is great) and even pure Date are fully capable to read it.

so, imho – go with iso-8601.

there are multiple answers how to add date serialization to json.dump.

👤Jerzyk

-1👍

I know this is an old question, but I came across it and it didn’t look answered so I’m answering this for other users on what I think Martijn wanted.

See Python documentation here for datetime strftime.
Datetime objects can be formatted like the example below which formats 2014-02-09 14:18:54.721021+00:00 into Feb. 9, 2014, 2:18 PM.

formatted_datetime_as_string = comment.date.strftime('%b. %d, %Y, %H:%M %p')

Then use formatted_datetime_as_string in your JSON data.

👤Fox

Leave a comment