python 'x days ago' to datetime

前端 未结 7 2040
谎友^
谎友^ 2021-01-11 09:35

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

相关标签:
7条回答
  • 2021-01-11 10:08

    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).

    0 讨论(0)
提交回复
热议问题