日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

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

1、思路說(shuō)明

可計(jì)算給定區(qū)間的時(shí)間差,即兩者之間共包含幾個(gè)月。然后由第一個(gè)月(開(kāi)始時(shí)間)逐漸累積,最后得到給定時(shí)間區(qū)間所有月份的清單。

2、時(shí)間差計(jì)算:我們可以使用第三方庫(kù) dateutil中的rrule.count函數(shù)來(lái)實(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é)果超過(guò)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]) #截取起始月份,寫(xiě)在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ù)字變成月份
當(dāng)前URL:http://www.5511xx.com/article/codsdcc.html