溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python輸入數(shù)字變成月份的示例

發(fā)布時間:2021-05-25 13:49:24 來源:億速云 閱讀:590 作者:小新 欄目:編程語言

這篇文章主要介紹python輸入數(shù)字變成月份的示例,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

1、思路說明

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

2、時間差計算:我們可以使用第三方庫 dateutil中的rrule.count函數(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、每月累積計算:在這里,我們可以使用for循環(huán)和range()函數(shù),根據(jù)總月數(shù),逐步累積,例如:2019.01-2019.05共5個月,從0到4迭代,從1+0=1到1+4=5,就可以得到所有月份;此外,當月迭代累積結果超過12時,將累積結果除以12取余,并將年份加1,就可以得到正確的年月時間。

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() #計算總月份數(shù)
 
if end
 
list_month=[]
 
year= int(str(start)[:7].split('-')[0]) #截取起始年份
 
for m in range(month_count): #利用range函數(shù)填充結果列表
 
month = int(str(start)[:7].split('-')[1]) #截取起始月份,寫在for循環(huán)里,作為每次迭代的累加基數(shù)
 
month = month +mif month > 12:if month%12 >0:
 
month= month%12 #計算結果大于12,取余數(shù)
 
if month==1:
 
year+= 1 #只需在1月份的時候對年份加1,注意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的五大特點是什么

python的五大特點:1.簡單易學,開發(fā)程序時,專注的是解決問題,而不是搞明白語言本身。2.面向對象,與其他主要的語言如C++和Java相比, Python以一種非常強大又簡單的方式實現(xiàn)面向對象編程。3.可移植性,Python程序無需修改就可以在各種平臺上運行。4.解釋性,Python語言寫的程序不需要編譯成二進制代碼,可以直接從源代碼運行程序。5.開源,Python是 FLOSS(自由/開放源碼軟件)之一。

以上是“python輸入數(shù)字變成月份的示例”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI