I have strings that show a date in the following format:
x minutes/hours/days/months/years ago
I need to parse that to a datetime using pyt
Sure you can do it. You just need a timedelta.
s = "3 days ago"
parsed_s = [s.split()[:2]]
time_dict = dict((fmt,float(amount)) for amount,fmt in parsed_s)
dt = datetime.timedelta(**time_dict)
past_time = datetime.datetime.now() - dt
As an aside, it looks like dateutil has a relativedelta
which acts like a timedelta, but the constructor also accepts months
and years
in the arguments (and apparently the arguments need to be integers).