How do I slice data before and after a certain date?

Question:

I have a pandas Series object with dates as index and values as a share price of a company. I would like to slice the data, so that I have let´s say a date 10.01.2022, and I want a slice from 3 previous dates and 5 next days from this date. Is that easily done? Or do I have to convert it, add/subtract those numbers from that date, and convert back? I´m a bit lost in all that datetime, strptime, to_datetime,…

Something like this:

date = "10.01.2022"

share_price = [date - 3 : date + 5]

Thank you

Answers:

You can use .loc[]. Both ends will be inclusive.

Example:

s = pd.Series([1,2,3,4,5,6],
              index = pd.to_datetime([
                '07.01.2022', '09.01.2022', '10.01.2022',
                '12.01.2022', '15.01.2022', '16.01.2022'
              ], dayfirst=True))

date = pd.to_datetime("10.01.2022", dayfirst=True)

s:

2022-01-07    1
2022-01-09    2
2022-01-10    3
2022-01-12    4
2022-01-15    5
2022-01-16    6
dtype: int64

date:

Timestamp('2022-01-10 00:00:00')
s.loc[date - pd.Timedelta('3d') : date + pd.Timedelta('5d')]


2022-01-07    1
2022-01-09    2
2022-01-10    3
2022-01-12    4
2022-01-15    5
dtype: int64

Edit:

To add business days:

from pandas.tseries.offsets import BDay

s.loc[date - BDay(3) : date + BDay(5)]
Answered By: Vladimir Fokow
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.