Finding the difference between two dates in months
Is it correct to find the difference between the two datetime
by month, as I found that months_to_maturity
my dataframe column df
stays the same before and after I find the difference. The code I am using is below:
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'))
thank
+3
source to share