There seems to be two different ways to format your dates using Django. The first takes advantage of Python’s built-in strftime
, so to format a date according to ISO8601:
mymodel.some_date_field.strftime("%Y%m%dT%H%m")
Giving you a date like 20050819T2031
.
<!-more->
Another approach is to format in the templates instead – then you can take advantage of Django’s filters. This formatting is based on the PHP date
function circa 4.1 (none of the formatting added in PHP 5.0 seems to be supported) – I assume using Simon Willison’s earlier work. I like the filters, but dislike the fact that I have one type of formatting in my models (and which other Python people will know) and another inside templates. It also doesn’t seem to be as flexible – for example to format a date in the same way as above (with a ‘T’ seperating date and time) I need two filters:
{{ mymodel.some_date_field|date:"Ymd" }}T{{ mymodel.some_date_field|date:"Gi" }}
I suppose if it bothers me that much I can always write my own filter…
7 Responses to “Formatting dates with Django”
First of all, I think ISO8601 is supposed to look like this: 2005-08-21T21:50Z.
Second of all, I was the one who sent in the patch to PHP that added the ‘c’ parameter to it’s date() function; it just gets a ISO8601 date. It should probably be added to Django as well.
Thanks Manuzhai – I tried the c format but of course it didn’t work. You should submit a patch!
As for the date thing, I was basing my format on the dates shown in the “hCalendar”:http://microformats.org/wiki/hcalendar spec which claim to be ISO8601 (of course it’s possible there is some flexibility in the spec).
Yes, these are two different forms of ISO8601 (basic and extended)
PS. if you’re interested in Java you may like http://joda-time.sourceforge.net
Don’t worry Stephen – I already swear by Joda for time and date handling in Java 🙂
I suppose a lot of designers who’ve dabbled in PHP will be familiar with that formatting and it’ll be easier for them. OTOH it _is_ a bit of a schlepp to be using the two systems side-by-side.
Just a minor note regarding your code example above: In Python’s strftime, minutes have the %M directive, not %m (which is for months). Sure it’s just a typo but beginners may be confused.
I know it’s a little late, but I came across this page searching for Template date filtering in Django and thought I would help others that are searching the same..
You can just escape the T like..
{{ someDate|date:’YmdTGi’ }}
Is there any difference between %Y and %y?