2

I have dataframe with timestamp values and i want to round off the timestamp to upper minute.

But i am not getting the desired output. I have used the following link to do the same:

 [1]: http://stackoverflow.com/questions/32344533/how-do-i-round-datetime-column-to-nearest-quarter-hour/32344636

how can i do that using pandas?

example:  output:
05:06:34  05:07
05:09:43  05:10

2 Answers2

1

You can write a function that will round up to the nearest minute:

Code:

import datetime as dt
def round_up_to_minute(timestamp):
    return timestamp + dt.timedelta(
        seconds=60-timestamp.second,
        microseconds=-timestamp.microsecond)

Test Code:

To apply it to a dataframe, you can do something like:

now = dt.datetime.now()
now_plus = now + dt.timedelta(minutes=1)
df = pd.DataFrame(data=[[now, now], [now_plus, now_plus]],
                  columns=['datetime', 'datetime_rounded'])

df['datetime_rounded'] = df['datetime_rounded'].apply(round_up_to_minute)

print(df)

Results:

                 datetime    datetime_rounded
0 2017-03-06 07:36:54.794 2017-03-06 07:37:00
1 2017-03-06 07:37:54.794 2017-03-06 07:38:00
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
0

Some time before September 2022 pandas incorporated DatetimeIndex.ceil().

dt_index = pd.to_datetime(['1970-01-01 05:06:34','1970-01-01 05:09:43'])
print(dt_index)
print(dt_index.ceil('1min'))

Outputs

DatetimeIndex(['1970-01-01 05:06:34', '1970-01-01 05:09:43'], dtype='datetime64[ns]', freq=None)
DatetimeIndex(['1970-01-01 05:07:00', '1970-01-01 05:10:00'], dtype='datetime64[ns]', freq=None)

DatetimeIndex also has floor() and round().

SpeedCoder5
  • 8,188
  • 6
  • 33
  • 34