views:

54

answers:

3

Hi,

I have a big search field, where users could type in any peice of text and it would search for it.

Now I have a requirement to add in dob to my search. I am not adding a new textbox with a dob picker. I just want users to be able to input a dob in a range of formats and it would figure it out.

IE users can search using any combination of these:

  • 25/08/1970
  • 25-08-1970
  • 1970/08/25
  • 1970-08-25

My program must figure out the dmy for each.

Is there a better way?

def parse(dob):
    for d in dob.split(" "):
       # find the dob
       if len(d) == 10:
           # its a dob
           if d[0:4].isdigit() # this is the year
               year = d[0:4]
               month = d[5:7]
               day = d[8:10]
            elif d[6:10].isdigit() # this is the year
               day = d[0:2]
               month = d[3:5]
               year= d[6:10]
+2  A: 

Python-dateutil should make your life much easier.

from dateutil.parser import parse as dparse
for each in ('25/08/1970', '25-08-1970', '1970/08/25', '1970-08-25'):
    dparse(each)

dparse(each) will return a datetime.datetime instance. You can pick up the date, month and year from the datetime instance.

Update

As mp0int pointed out, do remember to localize.

Manoj Govindan
You imported as dparse but called as parse.
sleepynate
Spotted it, fixed it. Thanks anyway :)
Manoj Govindan
A: 

You could use datetime.strptime ( http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior) or dateutil.parser.parse.

a = '25/08/1970'
b = dateutil.parser.parse(a)
sleepynate
I would argue against using `datetime.strptime` since the formats are not uniform. `dateutil.parser.parse` is a better choice.
Manoj Govindan
Seconded. I probably should have presented those in reverse order, but `strptime` is best as a failover for common date formats your users may enter that aren't included as part of `dateutil.parser'
sleepynate
+1  A: 

Dateutil.parser.parse is a nasty function and must be used carefully, such as

In [16]: parse('2010-05-01')
Out[16]: datetime.datetime(2010, 5, 1, 0, 0)

In [17]: parse('01-05-2010')
Out[17]: datetime.datetime(2010, 1, 5, 0, 0)

Localization is an important matter in date time format.

a = parse('01-05-2010')
a.astimezone(dateutil.tx.tzutc()) # not sure about dateutil.tx.tzutc()

probably this will resolve your problem, but i have not use it and i am not sure witch dateutil.tx function is what you need.

FallenAngel
+1 for mentioning Localization.
Manoj Govindan