1

I have a variable with 3 timestamps.

a = DatetimeIndex(['2016-01-26 20:30:00', '2016-01-26 21:30:00','2016-01-26 22:30:00'],
              dtype='datetime64[ns]', freq='H')

I've now since learned that the round function rounds according to these rules "when halfway between two integers the even integer is chosen."

a.round('H')
DatetimeIndex(['2016-01-26 20:00:00', '2016-01-26 22:00:00','2016-01-26 22:00:00'],
              dtype='datetime64[ns]', freq=None)

How I can make sure it rounds all 30 minute timestamps (e.g. 20:30, 19:30) to the next hour.

Thanks!

Edit:

I have tried the following function from Pandas Timestamp rounds 30 seconds inconsistently

def half_up_minute(x):
    m = (x - x.floor('H')).total_seconds() < 30   # Round True Down, False Up
    return x.where(m).floor('H').fillna(x.ceil('H'))

but get the following error:

TypeError: 'value' must be a scalar, passed: DatetimeIndex

borisvanax
  • 670
  • 1
  • 6
  • 15

1 Answers1

1

You can change function for replace fillna Series to second argument in Index.where and compare by 30 Minutes:

def half_up_minute(x):
    m = (x - x.floor('H')).total_seconds() < 30 * 60   
    return x.floor('H').where(m, x.ceil('H'))

print (half_up_minute(a))
DatetimeIndex(['2016-01-26 21:00:00', '2016-01-26 22:00:00',
               '2016-01-26 23:00:00'],
              dtype='datetime64[ns]', freq=None)   

a = pd.date_range('2016-01-26 20:30:00', periods=20, freq='10T')
print (a)
DatetimeIndex(['2016-01-26 20:30:00', '2016-01-26 20:40:00',
               '2016-01-26 20:50:00', '2016-01-26 21:00:00',
               '2016-01-26 21:10:00', '2016-01-26 21:20:00',
               '2016-01-26 21:30:00', '2016-01-26 21:40:00',
               '2016-01-26 21:50:00', '2016-01-26 22:00:00',
               '2016-01-26 22:10:00', '2016-01-26 22:20:00',
               '2016-01-26 22:30:00', '2016-01-26 22:40:00',
               '2016-01-26 22:50:00', '2016-01-26 23:00:00',
               '2016-01-26 23:10:00', '2016-01-26 23:20:00',
               '2016-01-26 23:30:00', '2016-01-26 23:40:00'],
              dtype='datetime64[ns]', freq='10T')

def half_up_minute(x):
    m = (x - x.floor('H')).total_seconds() < 30 * 60   
    return x.floor('H').where(m, x.ceil('H'))

print (half_up_minute(a))
DatetimeIndex(['2016-01-26 21:00:00', '2016-01-26 21:00:00',
               '2016-01-26 21:00:00', '2016-01-26 21:00:00',
               '2016-01-26 21:00:00', '2016-01-26 21:00:00',
               '2016-01-26 22:00:00', '2016-01-26 22:00:00',
               '2016-01-26 22:00:00', '2016-01-26 22:00:00',
               '2016-01-26 22:00:00', '2016-01-26 22:00:00',
               '2016-01-26 23:00:00', '2016-01-26 23:00:00',
               '2016-01-26 23:00:00', '2016-01-26 23:00:00',
               '2016-01-26 23:00:00', '2016-01-26 23:00:00',
               '2016-01-27 00:00:00', '2016-01-27 00:00:00'],
              dtype='datetime64[ns]', freq=None)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252