import time

import re
from datetime import datetime,timedelta
current_year = datetime.today().strftime("%Y")


def converting_time( ori_value):
    """
    对时间格式进行转换
    把 xxx秒前   xxx分前   xxx小时前  xxx天前   xxx月前   xxx年前
    转换为 2019-06-24 这种格式的时间

    params: ori_value
    return: target_style_time
    """

    current_year = datetime.today().strftime("%Y")
    num = int(re.findall('\d+', ori_value)[0])
    if '秒' in ori_value:
        s = (datetime.now() - timedelta(seconds=num))
    elif '分' in ori_value:
        s = (datetime.now() - timedelta(minutes=num))
    elif '时' in ori_value:
        s = (datetime.now() - timedelta(hours=num))
    elif '天' in ori_value:
        s = (datetime.now() - timedelta(days=num))
    elif '月' in ori_value:
        s = (datetime.now() - timedelta(days=num * 30))
    elif '年' in ori_value:
        s = (datetime.now() - timedelta(days=num * 365))
    else:
        ori_value += ',' + current_year
        s = datetime.strptime(ori_value, '%m %d %Y')
    temp_time = str(int(time.mktime(s.timetuple())))
    now = int(temp_time)

    time_array = time.localtime(now)
    target_style_time = time.strftime("%Y-%m-%d", time_array)
    return target_style_time
    # else:
    #     return None


result = converting_time('3月前')
print(result)

瑞0908
318 声望74 粉丝

一个一个解决