44

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

hernanavella
  • 5,462
  • 8
  • 47
  • 84

2 Answers2

66

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.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 1
    Can you briefly explain what was wrong with what I did? – hernanavella Sep 11 '14 at 21:37
  • 1
    Nothing. I just tried ur example in Pandas 0.14.1 and it works like you imagined. unutbu provided you with a workaround that should work with older versions of pandas (reasonably older, not stone-age ;) ) – K.-Michael Aye Sep 12 '14 at 01:56
  • I wonder how one can subtract the offset: I tried the following command but did not yield the expected result: ``` test[1].index - pd.DateOffset(hours=16). Any clue? – amonk Mar 26 '20 at 11:43
  • @amonk Did you try adding a negative offset? – Felix Mar 11 '21 at 21:12
0

Example of adding and subtracting time from a given datatime column in a given data frame.: using pd.Dateoffset()

 for index,row in insulin_dfs.iterrows():
        tm = row['date_time']
        print("Original Start Time :                  " + str(tm))
        start_time = tm + pd.DateOffset(minutes=-30)
        print("30 minutes prior Start Time :          " + str(start_time))
        end_time = tm + pd.DateOffset(hours=2)
        print("2 hours , 30 minutes from original Time" + str(end_time))
        break
output: 30 minutes prior to original time, and 2 hours after the time picked.

enter image description here

Note: You can use the + for adding time to existing time and - for subtracting time. you can pass multiple parameters simultaneously.

enter image description here

Arpan Saini
  • 4,623
  • 1
  • 42
  • 50