Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 708
piRSquared Avatar asked Mar 12 '23 04:03

piRSquared


2 Answers

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)
like image 142
jezrael Avatar answered Mar 14 '23 18:03

jezrael


alternatively you can use Timedelta():

In [49]: tidx + pd.Timedelta('15d')
Out[49]: DatetimeIndex(['2016-04-15', '2016-05-15'], dtype='datetime64[ns]', freq=None)

In [50]: tidx + pd.Timedelta(days=15)
Out[50]: DatetimeIndex(['2016-04-15', '2016-05-15'], dtype='datetime64[ns]', freq=None)
like image 28
MaxU - stop WAR against UA Avatar answered Mar 14 '23 16:03

MaxU - stop WAR against UA