defget_each_month(start_month, end_month):
start_month = start_month.replace('-','.')
end_month = end_month.replace('-','.')ifstr(start_month).count('.')!=1orstr(end_month).count('.')!=1:print("Parameter Error: Pls input a string such as '2019.01'")return[]ifint(str(start_month).split('.')[1])>12orint(str(end_month).split('.')[1])>12:print('Parameter Error: Pls input correct month range such as between 1 to 12')return[]ifint(str(start_month).split('.')[1])==0:print('Parameter Error: Pls input correct month range such as between 1 to 12')return[]
start = datetime.datetime.strptime(start_month,"%Y.%m")
end = datetime.datetime.strptime(end_month,"%Y.%m")
month_count = rrule.rrule(rrule.MONTHLY,dtstart=start,until=end).count()#计算总月份数if end < start:print("Parameter Error: Pls input right date range,start_month can't latter than end_month")return[]else:
list_month =[]
year =int(str(start)[:7].split('-')[0])#截取起始年份for m inrange(month_count):#利用range函数填充结果列表
month =int(str(start)[:7].split('-')[1])#截取起始月份,写在for循环里,作为每次迭代的累加基数
month = month + m
if month >12:if month%12>0:
month = month%12#计算结果大于12,取余数if month==1:
year +=1#只需在1月份的时候对年份加1,注意year的初始化在for循环外else:
month =12iflen(str(month))==1:
list_month.append(str(year)+'.0'+str(month))else:
list_month.append(str(year)+'.'+str(month))
list_month =[i.replace('.','-')for i in list_month]return list_month
get_each_month('2019-3','2020-01')['2019-03','2019-04','2019-05','2019-06','2019-07','2019-08','2019-09','2019-10','2019-11','2019-12','2020-01']