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?
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With