獲取兩個(gè)日期之間的所有月份

三種方法
1.比較基本的 獲取兩個(gè)日期之間相差多少月份,然后逐月相加,當(dāng)然,按12個(gè)月一循環(huán),nowMonth//12為需要加的年份,nowMonth%12+1為月份數(shù)。

import datetime
start = '2015-07-28'
end = '2021-01-12'

def getMonth_1(start,end):
    startDate = datetime.datetime.strptime(start, '%Y-%m-%d')
    endDate = datetime.datetime.strptime(end, '%Y-%m-%d')
    months = (endDate.year - startDate.year) * 12 + endDate.month - startDate.month
    print(months)
    month_range=[]
    for x in range(0,months+1):
        nowMonth=(startDate.month-1+x)
        date='%s-%s'%(startDate.year+nowMonth//12,nowMonth%12+1)
        month_range.append(date)
    return month_range

2.其實(shí)還是第一種思路,只是看著比較簡(jiǎn)潔

def getMonth_2(start,end):
    startDate = datetime.datetime.strptime(start, '%Y-%m-%d')
    endDate = datetime.datetime.strptime(end, '%Y-%m-%d')
    months = (endDate.year - startDate.year) * 12 + endDate.month - startDate.month
    print(months)
    month_range = ['%s-%s' % (startDate.year + mon // 12, mon % 12 + 1)
                   for mon in range(startDate.month - 1, startDate.month + months)]
    return month_range

3.取巧的一種方法 我們知道pandas 的date_range方法可以取到兩個(gè)日期之間所有的日期,然后我們?nèi)掌诟袷街蝗∧暝?,然后直接去重,就獲得了所需月份。(set去重之后變成無序,所以用sort重新排序一下)

import pandas as pd
def getMonth_3(start,end):
    date_list = [x for x in pd.date_range(start, end).strftime('%Y-%m')]
    month_range=list(set(date_list))
    month_range.sort(key=date_list.index)
    return month_range
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容