Python:日期差异(日期列与可变日期)

Python: Difference in dates (column of dates vs. variable date)

我有一列不同的日期,我想在数据框中添加另一列,以显示该列中的日期与我设置的各种日期之间的差异。

enddate = date(2021, 10, 15)

会是这样的:

我在下面试过但是 returns 错误:

from dateutil.relativedelta import relativedelta
metric_df['term'] = relativedelta(metric_df['maturity'], enddate).years

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

您是否考虑过使用日期时间减法?如果我有两个日期或日期时间,我可以减去它们以产生一个 timedelta 对象,即

start_date = date(2021,01,01)
end_date = date(2021,01,03)
delta = end_date - start_date
print(delta.days) # Should print 2

您也可以对列执行此操作,生成一列 timedelta 个对象。

relativedelta 不会给你小数年 afaik,但你可以自己轻松计算它们:

import pandas as pd

# dummy data
metric_df = pd.DataFrame({'maturity': ["9/22/2025", "11/10/2033", "3/1/2023"]})

# convert to datetime, so we can run calculations with date & time
metric_df['maturity'] = pd.to_datetime(metric_df['maturity'])

# to get fractional years, we calculate difference in days and divide
# by the average number of days per year:
metric_df['term'] = (metric_df['maturity'] - 
                         pd.Timestamp("2021-10-15")).dt.days / 365.25
metric_df['term']
0     3.937029
1    12.071184
2     1.374401
Name: term, dtype: float64