2015-07-10 50 views
3

我試圖選擇跨越兩個日期時間對象(row['orig_iss_dt']row['maturity_dt'])之間的每個年份的每年1月和7月的任何一天,然後將它插入my_dict。由於我的數據框df中的row['maturity_dt']是從今天(7月)起的6個月的幾倍,所以我認爲我的代碼如下所示。然而,由於我在四月,五月和六月的幾個月裏得到了一些date,所以它沒有按預期工作。我測試了monthdelta函數,它按預期工作。選擇兩個日期時間對象之間的某些月份

# Number of months between two datetime objects 
def monthdelta(d1, d2): 
    delta = 0 
    while True: 
     mdays = monthrange(d1.year, d1.month)[1] 
     d1 += timedelta(days=mdays) 
     if d1 <= d2: 
      delta += 1 
     else: 
      break 
    return delta 

#Trying to pick out Jan and July between the two datetimes and insert them into the dict 
for (i,row) in df.iterrows(): 
    my_dict = {} 
    date = datetime.datetime.strptime(row['maturity_dt'], '%Y-%m-%d %H:%M:%S.%f') #Setting date to be the maturity date 
    count = 0 
    for k in range(monthdelta(datetime.datetime.strptime(row['orig_iss_dt'], '%Y-%m-%d %H:%M:%S.%f'), datetime.datetime.strptime(row['maturity_dt'], '%Y-%m-%d %H:%M:%S.%f')), 0, -6): 
     #list_of_coupons.append(row.coupon) 
     date -= datetime.timedelta(6*30) #Reducing from the maturity date till it reaches orig_iss_dt 
     print(date) 
     count = count + 1 
     my_dict[count] = date 

謝謝你的解決方案

回答

0

的幾點思考:

1) 「日期 - = datetime.timedelta(6 * 30)」

我們利用一年時間這條線= 2015年,月= 1天= 30

dt = datetime.datetime(year=2015,month=1,day = 30) 
    for i in range(5): 
      dt -= datetime.timedelta(6*30) 
      print dt 

我們得到:

2014-08-03 00:00:00 
2014-02-04 00:00:00 
2013-08-08 00:00:00 
2013-02-09 00:00:00 
2012-08-13 00:00:00 

這不是七月。

2)我建議你的圖書館 「MonthDelta」 http://pythonhosted.org/MonthDelta/ ,可以解決您的問題是這樣的:萬一

for k in range(monthdelta(datetime.datetime.strptime(row['orig_iss_dt'], '%Y-%m-%d %H:%M:%S.%f'), datetime.datetime.strptime(row['maturity_dt'], '%Y-%m-%d %H:%M:%S.%f')), 0, -6): 
     #list_of_coupons.append(row.coupon) 
     date -= monthdelta.monthdelta(-6) #Reducing from the maturity date till it reaches orig_iss_dt 
     print(date) 
     count = count + 1 
     my_dict[count] = date 

3):

count = count + 1 
my_dict[count] = date 

與此代碼,你將永遠不會寫入my_dict [0]

相關問題