Reputation: 24
My program takes in data in the form of:
LASTNAME|FIRSTNAME|GENDER|DOB
The first thing I do is use regular expressions to detect the delimiter and split the fields. I allow a space, comma, or pipe as a delimiter. I know which field is DOB and have printed it out to ensure I'm not dealing with the wrong field.
My try code is as follows:
try:
#check if the fields are good
fields = re.split(r'[ ,|]+', line)
except:
#if not good: put it on the failure list
flist.append(line.replace('\n', ''))
LastName = fields[0]
FirstName = fields[1]
Gender = fields[2]
DOB = fields[3]
#one last try... make sure the DOB is good
try:
datetime.datetime.strptime(DOB, '%m/%d/%Y')
except:
flist.append(line.replace('\n', ''))
raise ValueError("DATE NOT IN RIGHT FORMAT")
I have fed the program multiple lines, and the one in particular I'm feeding:
NAME|FAKE|M|09/20/1987
ValueError: time data '09/20/1987' does not match format '%d/%m/%Y'
I've printed out the fields and I've tried converting "DOB" to a string. I've tried appending the .date()
to the end as well. I'm really not sure why it would be failing.
Upvotes: 0
Views: 147
Reputation: 499
@jonrsharpe is right. You're trying to parse a MM/DD/YYYY string as DD/MM/YYYY. If all of your dates are in the same format, you should be using '%d/%m/%Y'
as your format string.
Upvotes: 1