python中时间加减relativedelta

目录

官方链接
最近用到了月与月之间的加减, 发现 datetime.timedelta() 不支持这么大范围的时间加减
于是乎使用 relativedelta()

需要先安装时间处理-dateutil模块

pip install python-dateutil

relativedelta 使用
relativedelta() 同时也支持年 、月、日、周、时、分、秒的参数

from dateutil.relativedelta import relativedelta
import datetime
s_time= datetime.datetime.now()
print(s_time) # 2020-04-27 20:55:35.117521
#减一个月
stMonth = (s_time - relativedelta(months=1))
print(stMonth) # 2020-03-27 20:55:35.117521

stMonth = (s_time - relativedelta(year=1))
stMonth = (s_time - relativedelta(months=1))
stMonth = (s_time - relativedelta(days=1))
stMonth = (s_time - relativedelta(weeks=1))
stMonth = (s_time - relativedelta(hours=1))
stMonth = (s_time - relativedelta(minutes=1))
stMonth = (s_time - relativedelta(seconds=1))

你可能感兴趣的:(Python标准库使用,python)