How to subtract date with an integer and generate new columns based on its value

107 Views Asked by At

Lets say I have a column 'MEMBERSHIP_LENGTH' with the value is integer for example, the value is 100 means this id had been a member for 100 days. I want to know what date this id applied for a membership from today.

So what I am thinking is

df['APPLIED_DATE'] = pd.to_datetime('2023-01-21') - timedelta(days=df['MEMBERSHIP_LENGTH'])

but I got an error TypeError: unsupported type for timedelta days component: Series.

How should I do it?

1

There are 1 best solutions below

0
On

How about

from datetime import datetime, timedelta
df['APPLIED_DATE']=df['MEMBERSHIP_LENGTH'].apply(lambda x: datetime.today() - timedelta(days=x))
df
Out[28]: 
   MEMBERSHIP_LENGTH               APPLIED_DATE
0                100 2022-10-13 09:56:49.854174
1                101 2022-10-12 09:56:49.854174
2                200 2022-07-05 09:56:49.854174
3                201 2022-07-04 09:56:49.854174