Elif Y
Elif Y

Reputation: 251

Computing date range in Python using pandas

I have a data set below. I want to compute the date range between today and the date below for each row value.

date          stock_ticker   holding_days #today-date
2014-12-17    600268         
2015-01-21    002428
2014-11-19    600031
2015-02-26    600216
2014-12-20    601682

I know the datetime module can do this thing but I don't know how to sign value to each row.

Upvotes: 0

Views: 68

Answers (1)

EdChum
EdChum

Reputation: 394041

Are you wanting something like this:

In [294]:

df['holding_days'] = dt.datetime.now().date() - df['date']
df
Out[294]:
        date  stock_ticker  holding_days
0 2014-12-17        600268       77 days
1 2015-01-21          2428       42 days
2 2014-11-19        600031      105 days
3 2015-02-26        600216        6 days
4 2014-12-20        601682       74 days

In [323]:

def func(x):
    return len(pd.bdate_range(x['date'], dt.datetime.now().date()))

df['holding_bus_days'] = df.apply(lambda x: func(x), axis=1)
df
Out[323]:
        date  stock_ticker  holding_days  holding_bus_days
0 2014-12-17        600268       77 days                56
1 2015-01-21          2428       42 days                31
2 2014-11-19        600031      105 days                76
3 2015-02-26        600216        6 days                 5
4 2014-12-20        601682       74 days                53

Upvotes: 1

Related Questions