开发者

Format Django DateField as ISO format

I'm using Django to serve up some XML. Part of the requirements is that my dates are formatted as follows: 1969-12-31T18:33:28-开发者_运维技巧06:00

How can I output a DateField in Django in that format?


Introduced in Django 1.2, there is a template tag that will output what you wish:

{{ value|date:"c"}}

From the Django template documentation:

c | ISO 8601 Format | 2008-01-02T10:30:00.000123

Technically, this closer to W3-DTF, but close enough


Since Django is written in Python,

http://docs.python.org/library/datetime.html#datetime.datetime.isoformat

datetime(2002, 12, 25, tzinfo=TZ()).isoformat()


If you look under date in the Django documentation you'll see that a variety of formats for the date are supported. Basically in a template you need:

{{ value|date:"some format string" }} 

where the format string can be one of the ones defined under date on the page above or one of the custom ones defined under the now function (which includes ISO 8601 format) which is also on the page linked to above. I'm assuming that when you output to xml you do so in a similar way to a template for a normal web page.

Update (August 2014)

As indicated in another answer by Edgar R, as of version 1.2 onwards you can now use a built in switch to output the date in ISO 8601 format using format string: c


Check out these docs:

http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#date http://docs.djangoproject.com/en/dev/ref/settings/#setting-DATE_FORMAT http://docs.djangoproject.com/en/dev/ref/templates/builtins/#ttag-now

This should be enough for you to format your date any way, you wish.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜