views:

141

answers:

2

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 that 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?

+4  A: 

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.

Zack
+4  A: 

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.

uptimebox
In other words, the OP *should* be using Django forms, which will take care of this if you set input_formats correctly.
Daniel Roseman