根据日期获取指定月份列表
from datetime import date,datetime
from dateutil import rrule
from dateutil.relativedelta import relativedelta
class utils_funtion(object):
@staticmethod
def get_each_month_d(start_month, months):
"""获取月份列表"""
# relativedelta(years=+2, months=+8, days=+16,hours=+20, minutes=+54, seconds=+47)
sdate = datetime.strptime(start_month,'%Y-%m-%d')
date_list = []
for row in range(0,months):
edate = sdate + relativedelta(months=-row)
dtstr = edate.strftime('%Y-%m')
date_list.append(dtstr) #
date_list.sort() # 逆序排列
return date_list
monthlist = utils_funtion.get_each_month_d(datetime.today().strftime('%Y-%m-%d'),24)
print(monthlist)
结果
['2018-03', '2018-04', '2018-05', '2018-06', '2018-07', '2018-08', '2018-09', '2018-10', '2018-11', '2018-12', '2019-01', '2019-02', '2019-03', '2019-04', '2019-05', '2019-06', '2019-07', '2019-08', '2019-09', '2019-10', '2019-11', '2019-12', '2020-01', '2020-02']