Quick tip: Formatting date/time data in Django
There are situations where you obtain JSON data from an external source (e.g. via a REST-API) which contains date and time Information in the ISO 8601 format which looks like this:
2020-10-27T13:47:25.662Z
If you now want to output this date/time information in a readable manner in Django you can either manually reformat the strings of this data to the format you prefer using python string operations:
"2020-10-27T13:47:25.662Z" => "2020.10.27 13:47:25"
This works but there some more flexible way to do this in Django using built-in template tags and filters in the templating engine.
For this you use the datetime.strptime class method to create a date-time object which in turn could be reformatted in the Django HTML-template in any way you like.
For this you probably need to reformat your JSON data to contain date-time objects instead string of date/time string.
from datetime import datetime # Get JSON data response = requests.post(URL) json_data = response.json()['docs'] i=0 for entry in json_data: # create date-time objects by exactly defining the format of your date/time. Here we only use the first 19 chars because the miliseconds are not needed date_time_object = datetime.strptime(entry['created'][:19], "%Y-%m-%dT%H:%M:%S") # replace string of date/time with the date-time objects json_data[i]['created'] = date_time_object i = i+1
This list than can be used for the rendering of the Django HTML template:
template = loader.get_template('template.html') context = { 'json_data': json_data, } return HttpResponse(template.render(context, request))
In the Django template the the date/time formatting is defined similar as in PHP’s date() function:
<table> <tr> <th>Entry</th> <th>Created</th> </tr>
{% for entry in json_data %} <tr> <td> {{ entry.title }} </td> <td> {{ entry.created | date:"Y M d" }} </td> </tr>
{% endfor %} </table>
↑ back to top ↑