找出两个月内约会时间的差异

2024-04-19 19:18:29 发布

您现在位置:Python中文网/ 问答频道 /正文

当我发现我的dataframe dfmonths_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'))

谢谢


Tags: thetoindfdatetimedate差异row