Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly add hours to a pandas.tseries.index.DatetimeIndex?

I have a normal df.index that I would like to add some hours to it.

In [1]: test[1].index Out[2]:  <class 'pandas.tseries.index.DatetimeIndex'> [2010-03-11, ..., 2014-08-14] Length: 52, Freq: None, Timezone: None 

This is how the first element looks like:

In [1]: test[1].index[0] Out[2]: Timestamp('2010-03-11 00:00:00') 

So I try this to add the hours:

In [1]: test[1].index[0] + pd.tseries.timedeltas.to_timedelta(16, unit='h') 

However I get this:

Out[2]: Timestamp('2010-03-11 00:00:00.000000016') 

But I would like to get this:

Out[2]: Timestamp('2010-03-11 16:00:00') 

What I am missing?. The enviroment is Anaconda (latest) Python 2.7.7, iPython 2.2

Thanks a lot

like image 361
hernanavella Avatar asked Sep 11 '14 21:09

hernanavella


People also ask

Does pandas support time series?

pandas contains extensive capabilities and features for working with time series data for all domains. Using the NumPy datetime64 and timedelta64 dtypes, pandas has consolidated a large number of features from other Python libraries like scikits.

How can you change the index of a panda series?

reset_index() function to reset the index of the given series object and also we will be dropping the original index labels. Output : As we can see in the output, the Series. reset_index() function has reset the index of the given Series object to default.


1 Answers

You can use pd.DateOffset:

test[1].index + pd.DateOffset(hours=16) 

pd.DateOffset accepts the same keyword arguments as dateutil.relativedelta.


The problem you encountered was due to this bug which has been fixed in Pandas version 0.14.1:

In [242]: pd.to_timedelta(16, unit='h') Out[242]: numpy.timedelta64(16,'ns') 

If you upgrade, your original code should work.

like image 164
unutbu Avatar answered Oct 19 '22 12:10

unutbu