开发者

Django Date Input Parsing?

I'm trying to get a date for an event from a user. The input is just a simple html text input. My main problem is tha开发者_开发百科t I don't know how to parse the date.

If I try to pass the raw string, I get a TypeError, as expected.

Does Django have any date-parsing modules?


If you are using django.forms look at DateField.input_formats. This argument allows to define several date formats. DateField tries to parse raw data according to those formats in order.


Django doesn't, so to speak, by Python does. It seems I'm wrong here, as uptimebox's answer shows.

Say you're parsing this string: 'Wed Apr 21 19:29:07 +0000 2010' (This is from Twitter's JSON API)

You'd parse it into a datetime object like this:

import datetime

JSON_time = 'Wed Apr 21 19:29:07 +0000 2010'
my_time = datetime.datetime.strptime(JSON_time, '%a %b %d %H:%M:%S +0000 %Y')

print type(my_time)

You'd get this, confirming it is a datetime object:

<type 'datetime.datetime'>

More information on strptime() can be found here.


(In 2017), you could now use django.utils.dateparse


The DateField can be used outside of Django forms.

Example, when used {{ value|date:"SHORT_DATE_FORMAT" }} in template:

from django.forms import DateField
from django.utils import formats
# need '%d.%m.%Y' instead of 'd.m.Y' from get_format()
dformat = ('.' + formats.get_format("SHORT_DATE_FORMAT", lang=request.LANGUAGE_CODE)).replace('.', '.%').replace('-', '-%').replace('/', '/%')[1:]
dfield = DateField(input_formats=(dformat,))
<date> = dfield.to_python(<string>)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜