简体   繁体   English

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

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

I have a column of various dates and wanted to add another column to the dataframe that shows the difference between the dates in the column versus a date in various that I have set.我有一列不同的日期,并想向数据框中添加另一列,以显示该列中的日期与我设置的各种日期之间的差异。

在此处输入图片说明

enddate = date(2021, 10, 15)

Would something like:会喜欢:

在此处输入图片说明

I tried below but did returns error:我在下面尝试过,但确实返回错误:

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().

relativedelta doesn't give you fractional years afaik, but you can easily calculate them yourself: 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

Have you considered using datetime subtraction?您是否考虑过使用日期时间减法? If I have two dates or datetimes, I can subtract them to yield a timedelta object, ie如果我有两个日期或日期时间,我可以减去它们以产生一个timedelta对象,即

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

You can do this with columns too, yielding a column of timedelta objects.您也可以对列执行此操作,生成一列timedelta对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM