19天前等日期详细时间的函数

from datetime import datetime, timedelta
import random
import re


def get_time(time_str):
    # print(f'time_str: {time_str}')
    time_num = re.search('\d+', time_str).group(0)
    # print(time_num)

    if '秒' in time_str:
        yesterday = (datetime.now() - timedelta(seconds=int(time_num))).strftime('%Y-%m-%d %H:%M:%S')
    elif '分' in time_str:
        yesterday = (datetime.now() - timedelta(minutes=int(time_num))).strftime('%Y-%m-%d %H:%M:%S')
    elif '时' in time_str:
        random_minute = random.randint(0, 59)
        yesterday1 = datetime.now() - timedelta(hours=int(time_num))
        yesterday = yesterday1.replace(minute=random_minute).strftime('%Y-%m-%d %H:%M:%S')
    elif '天' in time_str:
        random_hour = random.randint(0, 23)
        random_minute = random.randint(0, 59)
        yesterday1 = datetime.now() - timedelta(days=int(time_num))
        yesterday = yesterday1.replace(hour=random_hour, minute=random_minute).strftime('%Y-%m-%d %H:%M:%S')
    elif '月' in time_str:
        ran_num = int(random.randint(0, 30))
        random_hour = random.randint(0, 23)
        random_minute = random.randint(0, 59)
        yesterday1 = datetime.now() - timedelta(days=(int(time_num) * 30) + ran_num)
        yesterday = yesterday1.replace(hour=random_hour, minute=random_minute).strftime('%Y-%m-%d %H:%M:%S')
    elif '年' in time_str:
        ran_num = int(random.randint(0, 364))
        random_hour = random.randint(0, 23)
        random_minute = random.randint(0, 59)
        yesterday1 = datetime.now() - timedelta(days=(int(time_num) * 365) + ran_num)
        yesterday = yesterday1.replace(hour=random_hour, minute=random_minute).strftime('%Y-%m-%d %H:%M:%S')
    else:
        yesterday = datetime.now().strftime('%Y-%m-%d %H:%M:%S')   # 现在的时间
    return yesterday


print(get_time('19天前'))

你可能感兴趣的:(python)