Search code examples
pythonpandaspython-datetime

add 15 days to every date in a pandas DatetimeIndex


I have a pandas DateTimeIndex. I want to add fifteen days to every date.

import pandas as pd    

tidx = pd.date_range(end='2016-04-30', freq='M', periods=2)

tidx

DatetimeIndex(['2016-03-31', '2016-04-30'], dtype='datetime64[ns]', freq='M')

I want:

DatetimeIndex(['2016-04-15', '2016-05-15'], dtype='datetime64[ns]', freq=None)

I've done:

pd.to_datetime([pd.datetime(t.year, t.month + 1, 15) for t in tidx])

This breaks as soon as t.month + 1 is greater than 12. Is there a generally accepted good way to do date math across an entire series?


Solution

  • I think you can use offsets, see docs:

    print (tidx + pd.offsets.Day(15))
    DatetimeIndex(['2016-04-15', '2016-05-15'], dtype='datetime64[ns]', freq=None)