Python 查找月内两个日期时间之间的差异
当我发现我的数据帧Python 查找月内两个日期时间之间的差异,python,pandas,Python,Pandas,当我发现我的数据帧df中的months\u to\u maturity列在我找到差异之前和之后保持不变时,这是找到两个datetimes之间月数差异的正确方法吗。我使用的代码如下: todays_date = datetime.date.today() #Converting to datetime datenow = datetime.datetime.combine(todays_date, datetime.datetime.min.time()) # Function to find
df
中的months\u to\u maturity
列在我找到差异之前和之后保持不变时,这是找到两个datetime
s之间月数差异的正确方法吗。我使用的代码如下:
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'))
todays\u date=datetime.date.today()
#转换为日期时间
datenow=datetime.datetime.combine(todays\u date,datetime.datetime.min.time())
#函数查找两个datetime对象之间的月差
def monthdelta(d1、d2):
增量=0
尽管如此:
mdays=monthrange(d1.年,d1.月)[1]
d1+=timedelta(天数=mdays)
如果d1你为什么不用数学呢
from datetime import datetime
def month_delta(d0, d1):
dy = d0.year - d1.year
dm = d0.month - d1.month
return dm + (dy*12)