Formatting date times provided as strings in Django

Tristan Brotherton picture Tristan Brotherton · Jun 12, 2009 · Viewed 23.7k times · Source

In my Django application I get times from a webservice, provided as a string, that I use in my templates:

{{date.string}}

This provides me with a date such as:

2009-06-11 17:02:09+0000

These are obviously a bit ugly, and I'd like to present them in a nice format to my users. Django has a great built in date formatter, which would do exactly what I wanted:

{{ value|date:"D d M Y" }}

However this expects the value to be provided as a date object, and not a string. So I can't format it using this. After searching here on StackOverflow pythons strptime seems to do what I want, but being fairly new to Python I was wondering if anyone could come up with an easier way of getting date formatting using strings, without having to resort to writing a whole new custom strptime template tag?

Answer

Jarret Hardie picture Jarret Hardie · Jun 12, 2009

You're probably better off parsing the string received from the webservice in your view code, and then passing the datetime.date (or string) to the template for display. The spirit of Django templates is that very little coding work should be done there; they are for presentation only, and that's why they go out of their way to prevent you from writing Python code embedded in HTML.

Something like:

from datetime import datetime
from django.shortcuts import render_to_response

def my_view(request):
    ws_date_as_string = ... get the webservice date
    the_date = datetime.strptime(ws_date, "%Y-%m-%d %H:%M:%S+0000")
    return render_to_response('my_template.html', {'date':the_date})

As Matthew points out, this drops the timezone. If you wish to preserve the offset from GMT, try using the excellent third-party dateutils library, which seamlessly handles parsing dates in multiple formats, with timezones, without having to provide a time format template like strptime.