新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python輸入數(shù)字變成月份
1、思路說明

可計(jì)算給定區(qū)間的時(shí)間差,即兩者之間共包含幾個(gè)月。然后由第一個(gè)月(開始時(shí)間)逐漸累積,最后得到給定時(shí)間區(qū)間所有月份的清單。
2、時(shí)間差計(jì)算:我們可以使用第三方庫 dateutil中的rrule.count函數(shù)來實(shí)現(xiàn)。
Impor tdatetime from dateutil importrrule
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、每月累積計(jì)算:在這里,我們可以使用for循環(huán)和range()函數(shù),根據(jù)總月數(shù),逐步累積,例如:2019.01-2019.05共5個(gè)月,從0到4迭代,從1+0=1到1+4=5,就可以得到所有月份;此外,當(dāng)月迭代累積結(jié)果超過12時(shí),將累積結(jié)果除以12取余,并將年份加1,就可以得到正確的年月時(shí)間。
importdatetimefrom dateutil importrruledefget_each_month(start_month, end_month):if str(start_month).count('.') != 1 or str(end_month).count('.') != 1:print("Parameter Error: Pls input a string such as '2019.01'")return[]if int(str(start_month).split('.')[1]) > 12 or int(str(end_month).split('.')[1]) > 12:print('Parameter Error: Pls input correct month range such as between 1 to 12')return[]if int(str(start_month).split('.')[1]) == 0 or int(str(end_month).split('.')[1]) == 12: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() #計(jì)算總月份數(shù)
if end
list_month=[]
year= int(str(start)[:7].split('-')[0]) #截取起始年份
for m in range(month_count): #利用range函數(shù)填充結(jié)果列表
month = int(str(start)[:7].split('-')[1]) #截取起始月份,寫在for循環(huán)里,作為每次迭代的累加基數(shù)
month = month +mif month > 12:if month%12 >0:
month= month%12 #計(jì)算結(jié)果大于12,取余數(shù)
if month==1:
year+= 1 #只需在1月份的時(shí)候?qū)δ攴菁?,注意year的初始化在for循環(huán)外
else:
month= 12
if len(str(month))==1:
list_month.append(str(year)+ '.0' +str(month))else:
list_month.append(str(year)+ '.' +str(month))return list_month以上就是python輸入數(shù)字變成月份的方法,基本的流程分享給大家,看懂后可以進(jìn)行實(shí)例部分的嘗試。更多Python學(xué)習(xí)指路:創(chuàng)新互聯(lián)Python教程
本文教程操作環(huán)境:windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。
分享題目:創(chuàng)新互聯(lián)Python教程:python輸入數(shù)字變成月份
文章位置:http://m.fisionsoft.com.cn/article/codsdcc.html


咨詢
建站咨詢
