2017-07-04 108 views
0
>>> M1 
['month:12;year:2006', 'month:7;year:2010'] 
>>> M2 
['month:5;year:2006', 'month:3;year:2010'] 
>>> M3 
['year:2006'; 'month:4;year:2010'] 

我有3個列表項M1, M2, M3計算時間段使用python

M1[0] is the Start date 
M2[0] is the End date 

是有可能的名單這樣轉換並執行計算

M1 = 12/2006, 7/2010 
M2 = 5/2006, 3/2010 
M3 = 0/2006, 4/2010 

我要的是計算它們之間的差異就像

M1Diff = 43 months 
M2Diff = 52 months 
M3Diff = 51 months 
+5

這當然是可以的。你嘗試了什麼? –

+1

月可以是0?我的意思是第0個月是什麼? –

+0

@AhsanulHaque,這可能是有道理的,0 - 1月11日 - 12月。但是,他已經有12個,這很奇怪:P –

回答

1

我將展示如何做到這一點,爲第一,以同樣的方式可以實現

def diff_month(d1, d2): 
    return abs((d1.year - d2.year) * 12 + d1.month - d2.month) 


M1=['month:12;year:2006', 'month:7;year:2010'] 
d1 = datetime.strptime(M1[0], 'month:%m;year:%Y') 
d2 = datetime.strptime(M1[1], 'month:%m;year:%Y') 

diff_month(d1, d2) 

在這種方法只用於循環對所有的最新集合。

希望這會有幫助