Home > Mobile >  Pandas Days after Date
Pandas Days after Date

Time:10-30

Hello I have a Dataframe like this in pandas

import pandas as pd
df = pd.DataFrame({'date': ['2022-10-01', '2022-10-04', '2022-10-17'],
                   'value': [100, 110, 95]})

How can I subtract the date from a default value?

I've tried it like this

'2022-10-20' - df['date']

but got an error

TypeError: unsupported operand type(s) for -: 'str' and 'str'

I want to calculate the values 19, 16, 3

CodePudding user response:

You can use a datetime object to calculate the difference and then get the number of days with the .dt accessor

Try this:

from datetime import datetime
(datetime(2022, 10, 20) - pd.to_datetime(df["date"])).dt.days

CodePudding user response:

You can use pandas.Timestamp and to_datetime:

(pd.Timestamp('2022-10-20') - pd.to_datetime(df['date'])).dt.days

Or:

pd.to_datetime(df['date']).rsub(pd.Timestamp('2022-10-20')).dt.days
  • Related