3

I have a field named 'MATURITY' in a dataframe. One sample date looks like this:

2026-05-21

I'm trying to add a new field to the dataframe and find the difference between each maturity date and today. How can I do that? I tried the following:

df['DaysToMaturity'] = pd.to_datetime((df['MATURITY'] - date.today()).days)

That gives me this error:

TypeError: unsupported operand type(s) for -: 'DatetimeIndex' and 'datetime.date'

That should be pretty close, I believe, but obviously something is off here. Thoughts?

ASH
  • 18,040
  • 13
  • 61
  • 153
  • Does this answer your question? [Add column with number of days between dates in DataFrame pandas](https://stackoverflow.com/questions/22132525/add-column-with-number-of-days-between-dates-in-dataframe-pandas) – AMC Feb 08 '20 at 01:28

2 Answers2

8

Use pandas.Timestamp

df['DaysToMaturity'] = (df['MATURITY'] - pd.Timestamp('now')).dt.days
piRSquared
  • 265,629
  • 48
  • 427
  • 571
  • Thanks, that worked, but the formatting is wacky. I'm seeing this: 1970-01-01 00:00:00.000002504 The 2504 is the number of days, but how can I just get that? – ASH Jul 12 '19 at 17:20
  • df['DaysToMaturity'] = pd.to_numeric(df['DaysToMaturity']) – ASH Jul 12 '19 at 18:21
2

try this:

from datetime import date
f_date = date.today()
l_date = date(2026, 5, 21)
delta = l_date - f_date
print(delta.days)
hmn Falahi
  • 684
  • 5
  • 20