Rounding time in Python Rounding time in Python python python

Rounding time in Python


For a datetime.datetime rounding, see this function:https://stackoverflow.com/a/10854034/1431079

Sample of use:

print roundTime(datetime.datetime(2012,12,31,23,44,59,1234),roundTo=60*60)2013-01-01 00:00:00


How about use datetime.timedeltas:

import timeimport datetime as dthms=dt.timedelta(hours=20,minutes=11,seconds=13)resolution=dt.timedelta(seconds=10)print(dt.timedelta(seconds=hms.seconds%resolution.seconds))# 0:00:03resolution=dt.timedelta(minutes=10)print(dt.timedelta(seconds=hms.seconds%resolution.seconds))# 0:01:13


This will round up time data to a resolution as asked in the question:

import datetime as dtcurrent = dt.datetime.now()current_td = dt.timedelta(    hours = current.hour,     minutes = current.minute,     seconds = current.second,     microseconds = current.microsecond)# to seconds resolutionto_sec = dt.timedelta(seconds = round(current_td.total_seconds()))print(dt.datetime.combine(current, dt.time(0)) + to_sec)# to minute resolutionto_min = dt.timedelta(minutes = round(current_td.total_seconds() / 60))print(dt.datetime.combine(current, dt.time(0)) + to_min)# to hour resolutionto_hour = dt.timedelta(hours = round(current_td.total_seconds() / 3600))print(dt.datetime.combine(current, dt.time(0)) + to_hour)