Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 627
Dane Larsen Avatar asked May 03 '10 07:05

Dane Larsen


2 Answers

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.

like image 93
uptimebox Avatar answered Sep 30 '22 20:09

uptimebox


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.

like image 32
Zack Avatar answered Sep 30 '22 19:09

Zack