1. 程式人生 > >python簡單獲取兩個日期之間的年度、月度、天數差的方法

python簡單獲取兩個日期之間的年度、月度、天數差的方法

    最近因為要做一些簡單的結算工作,裡面有一些規則需要對年度、月份、天數進行比較,在網上查了半天,忽然發現python進行年度、月份、日期處理這麼難?!居然只是要計算兩個時間之間的月份差,還要數十行程式碼!     有點不敢相信,所以自己寫了一個日期和月份差的函式,現推薦給大家(通過datetime包實現):import datetimedef days(str1,str2):
    date1=datetime.datetime.strptime(str1[0:10],"%Y-%m-%d")
    date2=datetime.datetime.strptime(str2[0:10],"%Y-%m-%d")
    num=(date1-date2).days
    return num

def months(str1,str2):
    year1=datetime.datetime.strptime(str1[0:10],"%Y-%m-%d").year
    year2=datetime.datetime.strptime(str2[0:10],"%Y-%m-%d").year
    month1=datetime.datetime.strptime(str1[0:10],"%Y-%m-%d").month
    month2=datetime.datetime.strptime(str2[0:10],"%Y-%m-%d").month
    num=(year1-year2)*12+(month1-month2)
    return num

輸入days('2018-04-23 08:18:09','2017-03-21 10:19:33') ,返回398輸入months('2018-01-23 08:18:09','2017-03-21 10:19:33'),返回10