当我发现我的dataframe df
的months_to_maturity
列在我找到差异之前和之后保持不变时,这是以月为单位找出两个datetime
之间差异的正确方法吗。我使用的代码如下:
todays_date = datetime.date.today()
#Converting to datetime
datenow = datetime.datetime.combine(todays_date, datetime.datetime.min.time())
# Function to find the difference in months between the 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
# Re-assiging months_to_maturity in df with the difference between the two datetimes
for (i,row) in df.iterrows():
row['months_to_maturity'] = monthdelta(datenow, datetime.datetime.strptime(row['maturity_dt'], '%Y-%m-%d %H:%M:%S.%f'))
谢谢
你为什么不用数学呢?你知道吗
相关问题 更多 >
编程相关推荐