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
谢谢你的解决方案