Husnain Iqbal
Husnain Iqbal

Reputation: 89

Cant get the number of days in pandas.. it carries date from another column

enter image description hereI have been trying to get number days (SCN Date - Today). I have tried different approaches my latest attempt is as below. It puts date from SCN Date in `Today'

I just need to get number of days in numeric form.

import pandas as pd
eod = pd.read_excel('df.xlsx')
import datetime
eod['Today'] =  datetime.date.today()
eod['Today'] = pd.Series(eod['Today'])
eod['Today'] = pd.Series(eod['SCN Date'])
eod['Days'] = eod['Today']-eod['SCN Date']

Upvotes: 0

Views: 40

Answers (2)

jezrael
jezrael

Reputation: 862591

Use Timestamp with Timestamp.floor for datetimes with no times, extract and convert output timedeltas to days by Series.dt.days, solution is without new column:

eod = pd.read_excel('df.xlsx')

eod['Days'] = (pd.Timestamp('now').floor('d') - eod['SCN Date']).dt.days

Or if necessary convert column to datetimes use to_datetime:

eod['Days'] = (pd.Timestamp('now').floor('d') - pd.to_datetime(eod['SCN Date'])).dt.days

Upvotes: 1

Kristian
Kristian

Reputation: 2505

First, this is how to get date difference in days with python datetime:

date1 = datetime.datetime.now()
date2 = datetime.datetime.now()
delta = date2 - date1
print(delta.days)

Then if we apply it to pandas:

import pandas as pd
eod = pd.read_excel('Documents/sample.xlsx')
import datetime
eod["Today"] = datetime.datetime.now()
eod["Delta"] = eod["Today"] - eod["SCN Date"]
eod["DeltaDays"] = eod["Delta"].apply(lambda x: x.days)

The last line: eod["DeltaDays"] = eod["Delta"].apply(lambda x: x.days) means that, for each data in column "Delta", take it's "days" property and save it to column "DeltaDays"

Result:

>>> eod
     SCN Date Name                      Today                    Delta  DeltaDays
0  2020-01-01    a 2020-09-10 14:20:30.046694 253 days 14:20:30.046694        253
1  2020-01-02    b 2020-09-10 14:20:30.046694 252 days 14:20:30.046694        252
2  2020-01-03    c 2020-09-10 14:20:30.046694 251 days 14:20:30.046694        251
3  2020-01-04    d 2020-09-10 14:20:30.046694 250 days 14:20:30.046694        250
4  2020-01-05    e 2020-09-10 14:20:30.046694 249 days 14:20:30.046694        249
5  2020-01-06    f 2020-09-10 14:20:30.046694 248 days 14:20:30.046694        248
6  2020-01-07    e 2020-09-10 14:20:30.046694 247 days 14:20:30.046694        247
7  2020-01-08    f 2020-09-10 14:20:30.046694 246 days 14:20:30.046694        246
8  2020-01-09    f 2020-09-10 14:20:30.046694 245 days 14:20:30.046694        245
9  2020-01-10    f 2020-09-10 14:20:30.046694 244 days 14:20:30.046694        244
10 2020-01-11    f 2020-09-10 14:20:30.046694 243 days 14:20:30.046694        243

Upvotes: 0

Related Questions