Rounding time off to the nearest second - Python

Without any extra packages, a datetime object can be rounded to the nearest second with the following simple function:

import datetime as dt

def round_seconds(obj: dt.datetime) -> dt.datetime:
    if obj.microsecond >= 500_000:
        obj += dt.timedelta(seconds=1)
    return obj.replace(microsecond=0)

If anyone wants to round a single datetime item off to the nearest second, this one works just fine:

pandas.to_datetime(your_datetime_item).round('1s')

If you're using pandas, you can just round the data to the nearest second using dt.round -

df

                timestamp
0 2017-06-25 00:31:53.993
1 2017-06-25 00:32:31.224
2 2017-06-25 00:33:11.223
3 2017-06-25 00:33:53.876
4 2017-06-25 00:34:31.219
5 2017-06-25 00:35:12.634

df.timestamp.dt.round('1s')

0   2017-06-25 00:31:54
1   2017-06-25 00:32:31
2   2017-06-25 00:33:11
3   2017-06-25 00:33:54
4   2017-06-25 00:34:31
5   2017-06-25 00:35:13
Name: timestamp, dtype: datetime64[ns]

If timestamp isn't a datetime column, convert it first, using pd.to_datetime -

df.timestamp = pd.to_datetime(df.timestamp)

Then, dt.round should work.


The question doesn't say how you want to round. Rounding down would often be appropriate for a time function. This is not statistics.

rounded_down_datetime = raw_datetime.replace(microsecond=0)