python输入数字变成月份
python输入数字变成月份
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:Plsinputcorrectmonthrangesuchasbetween1to12')return[]ifint(str(start_month).split('.')[1])==0orint(str(end_month).split('.')[1])==12:print('ParameterError:Plsinputcorrectmonthrangesuchasbetween1to12')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,注意year的初始化在for循环外
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学习教程请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python函数标注是什么
python函数标注是什么在参数的使用方法中,还有一种解包的情况是需要我们掌握的。比如,将列表或者字典的值转换为函数的参数,就需要用到参数解...详情>>
2023-11-14 14:13:35
python正负索引的使用
python正负索引的使用本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、说明使用正索引(从左至右)、负索引(从右至左)访问元素,时...详情>>
2023-11-14 13:45:04
python垃圾回收的机制过程
python垃圾回收的机制过程本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、步骤(1)收集所有容器对象(list,dict,tuple,customClas...详情>>
2023-11-14 13:05:15
pythontry语句的执行原理
pythontry语句的执行原理1、原理分析(1)执行try子句(try和except关键字之间的多行语句)。(2)如果没有异常发生,则跳过except子句并完成try语句...详情>>
2023-11-14 09:37:35热门推荐
技术干货






