Sometimes, regex really is the right tool for the job - I don't think the following code is too complex, and seems pretty explicit in its intention:
from dateutil.parser import parse
import re
s = "[datetime.date(2003, 2, 4), datetime.date(2003, 2, 6)]"
c = re.compile("datetime.date\((.*?)\)")
date_strings = c.findall(s)
print [parse(date_string).date() for date_string in date_strings]
If you don't have access to the dateutil
module, then you can also roll your own parse
function:
import datetime
import re
def parse(s):
year, month, day = s.split(', ')
year, month, day = int(year), int(month), int(day)
return datetime.date(year, month, day)
s = "[datetime.date(2003, 2, 4), datetime.date(2003, 2, 6)]"
c = re.compile("datetime.date\((.*?)\)")
date_strings = c.findall(s)
print [parse(date_string) for date_string in date_strings]