Parse Multiple Dates Using Dateutil
I am trying to parse multiple dates from a string in Python with the help of this code, from dateutil.parser import _timelex, parser a = 'Approve my leave from first half of 12/10/
Solution 1:
Your parser couldn't handle the "second"
found by timesplit
,if you set the fuzzy
param to be True
, it doesn't break but nor does it produce anything meaningful.
from cStringIO importStringIO
for item intimesplit(StringIO(a)):
print "Found:", item
print "Parsed:", p.parse(StringIO(item),fuzzy=True)
out:
Found:12102012Parsed:2012-12-10 00:00:00Found:secondParsed:2013-01-11 00:00:00Found:20102012Parsed:2012-10-20 00:00:00
You have to fix the timesplitting or handle the errors:
opt1:
lose the info.hms
from timetoken
opt2:
from cStringIO import StringIO
for item in timesplit(StringIO(a)):
print"Found:", item
try:
print"Parsed:", p.parse(StringIO(item))
except ValueError:
print'Not Parsed!'
out:
Found:12102012Parsed:2012-12-10 00:00:00Found:secondNotParsed!Parsed: Found:20102012Parsed:2012-10-20 00:00:00
Solution 2:
If you need only dates, could extract it with regex and works with dates.
a = "Approve my leave from first half of 12/10/2012 to second half of 20/10/2012 "importrepattern= re.compile('\d{2}/\d{2}/\d{4}')
pattern.findall(a)
['12/10/2012', '20/10/2012']
Post a Comment for "Parse Multiple Dates Using Dateutil"