乐趣区

关于python:python将特殊时间格式-几天前-几月前-几年前-几周前-转换为xxxxxxxx格式

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)
退出移动版