convert the string in the form "6 days ago" to a date

There are different lines: "1 day ago", "5 days ago", "3 month ago", etc. How can I convert them to a date like: 2019-04-03

In the pcp, there is date("Y-m-d", strtotime("3 days ago"))

Author: MaxU, 2019-04-03

1 answers

In general terms, I would do this:

from datetime import date    
from dateutil.relativedelta import *
import re

str1 = "2 дня назад"
str2 = "3 месяца назад"
str3 = "lorem ipsum"

def getpastdate(a:str):
    num=re.findall(r'\d+', a)
    if num:
        num = int(num[0])
        if re.search(r'день|дня|дней',a):
            past = date.today() + relativedelta(days=-num)
        elif re.search(r'месяц', a):
            past = date.today() + relativedelta(months=-num)
        else:
            past = None
    else:
        past = None
    return past

print(getpastdate(str1))
# 2019-04-01
print(getpastdate(str2))
# 2019-01-03
print(getpastdate(str3))
# None
 6
Author: strawdog, 2019-04-04 11:15:16