Calculate number of days from date time column to a specific date - pandas

Viewed 36

I have a df as shown below.

df:

ID    open_date        limit
1     2020-06-03       100
1     2020-06-23       500
1     2019-06-29       300
1     2018-06-29       400

From the above I would like to calculate a column named age_in_days. age_in_days is the number of days from open_date to 2020-06-30.

Expected output

ID    open_date        limit     age_in_days
1     2020-06-03       100       27
1     2020-06-23       500       7
1     2019-06-29       300       367
1     2018-06-29       400       732
1 Answers

Make sure open_date in datetime dtype and subtract it from 2020-06-30

df['open_date'] = pd.to_datetime(df.open_date)

df['age_in_days'] = (pd.Timestamp('2020-06-30') - df.open_date).dt.days


Out[209]:
   ID  open_date  limit  age_in_days
0   1 2020-06-03    100           27
1   1 2020-06-23    500            7
2   1 2019-06-29    300          367
3   1 2018-06-29    400          732
Related