python输入数字变成月份
发布时间:2024-07-16 10:03:27

1、思路说明
给定范围的时差可以计算,即两者之间包含几个月。然后从第一个月(开始时间)逐渐积累,最后得到给定时间范围内所有月份的清单。
2、时差计算:我们可以使用第三方库 dateutil中的rrule.实现count函数。
Importdatetimefromdateutilimportrrule
start=datetime.datetime.strptime('2019.01','%Y.%m')
end=datetime.datetime.strptime('2019.05','%Y.%m')print(start.month)
rrule.rrule(rrule.MONTHLY,dtstart=start,until=end).count()3、每月积累计算:在这里,我们可以使用for循环和range()函数,根据总月数,逐步积累,例如:2019.01-2019.05共5个月,从0到4迭代,从1+0=1到1+4=5,即可获得全部月份;另外,当月积累累积结果超过12时,将累积结果除以12取余,并将年份加1,即可获得正确的年月时间。
importdatetimefromdateutilimportrruledefget_each_month(start_month,end_month):ifstr(start_month).count('.')!=1orstr(end_month).count('.')!=1:print("ParameterError:Plsinputastringsuchas'2019.01'")return[]ifint(str(start_month).split('.')[1])>12orint(str(end_month).split('.')[1])>12:print('ParameterError:Plsinputcorectmonthrangesuchasbetwen1to12')return[]ifint(str(start_month).split('.')[1]=0orintt)(str(end_month).split('.')[1])==12:print('ParameterError:Plsinputcorectmonthrangesuchasbetwen1to12')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()#计算总月份数
ifend
list_month=[]
year=int(str(start)[:7].split('-')[0])#截取起始年份
forminrange(month_count):#使用range函数填充结果列表
month=int(str(start)[:7].split('-')[1])#截取起始月份,作为每次迭代的累加基数,写在for循环中
month=month+mifmonth>12:ifmonth%12>0:
month=month%12#计算结果大于12,取余数
ifmonth==1:
year+=1#1月份只需加1年份,注意for循环外year的初始化
else:
month=12
iflen(str(month))==1:
list_month.append(str(year)+'.0'+str(month))else:
list_month.append(str(year)+'.'+str(month))returnlist_month以上是python输入数字成月的方法,基本流程与大家分享,理解后可以尝试实例部分。更多Python学习指导:python基础教程
本文教程操作环境:windows7系统Python 3.9.1,DELL G3电脑。
下一篇 Python类属性如何使用
