Python 计算时间

from datetime import datetime, timedelta

now_time = datetime.now()
print(now_time)


def change_time(time_str, days=0, hours=0, minutes=0):
    date_str = time_str
    if type(time_str) == str:
        date_str = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
    date_str_ret = date_str + timedelta(days=days, hours=hours, minutes=minutes)
    print(date_str_ret)


# 30分钟后
change_time(time_str=now_time, minutes=30)
# 2小时之前
change_time(time_str=now_time, hours=-2)
# 明天
change_time(time_str=now_time, days=1)
# 15天-2小时-20分钟后
change_time(time_str=now_time, days=15, hours=2, minutes=20)

你可能感兴趣的:(Python)