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
謝謝你的解決方案