啥也不说了,直接上代码。
首先需要导入python自带的datetime模块。
import datetime
# 导入日期扩展库
from dateutil.relativedelta import relativedelta
# 当前 年 月 日
today = datetime.date.today()
# 下下个月
last_2_month = today + relativedelta(months=+2) # 下两个月,下N个月参数为(months=-N)
next_two_months = datetime.datetime.strftime(last_2_month, "%Y-%m")
# 下月
last_2_month = today + relativedelta(months=+1) # 下个月,下个月参数为(months=-1)
next_month = datetime.datetime.strftime(last_2_month, "%Y-%m")
# 本月(年月)
str_now = datetime.datetime.strftime(today, "%Y-%m")
# 上月
last_month = today + datetime.timedelta(days=-today.day)
str_last = datetime.datetime.strftime(last_month, "%Y-%m")
# 上2个月
last_2_month = today + relativedelta(months=-2) # 上两个月,上N个月参数为(months=-N)
two_months = datetime.datetime.strftime(last_2_month, "%Y-%m")
###所有输出结果都是字符串类型(例2019-08),可以根据自己的需求格式化时间输出。
作者:weixin_43108474
来源:CSDN
版权声明:本文为博主原创文章,转载请附上博文链接!