The function below can round any time string to hours, minutes, seconds by setting parmeter 'unit', default is the smallest format of ts. Parameter 'ts' is the time string you want to round, the fuction accept multiple time formats. With parmeter 'rnd' you can set the number you want to round at, default is 1. With parmeter 'frm' you can set the format of the output string, as default the function takes the format of ts. Just play with the function and you will see how easy it will be. The function even convert time strings between 12 and 24 hours format and vice versa. All this with a minimum on import.
def toNearestTime(ts, unit=None, rnd=1, frm=None):
''' round to the Nearest Time
param ts = auto recognize the most time patterns : not date-time
param unit = specify unit wich must be rounded 'sec' or 'min' or 'hour', default is the smallest unit of ts :
param rnd = to which number you will round, the default is 1 :
param frm = the output (return) format of the time string you want, as default the function take the ts format'''
from time import strftime, gmtime, strptime
ustp = ["AM", 'PM']
if any(e in ts for e in ustp):
time12_pat = {'%I:%M%p': 'm', '%I:%M %p': 'm', '%I:%M:%S%p': 'se', '%I:%M:%S %p': 'se', '%I%M%p': 'm', '%I%M %p': 'm', '%I%M%S%p': 'se', '%I%M%S %p': 'se'}
for p, u in time12_pat.items():
try:
ts = strftime('%H:%M:%S', strptime(ts, p))
break
except:
continue
sf = p
unit = time12_pat[sf] if unit is None else unit
else:
time24_pat = {'%H:%M': 'm', '%H:%M:%S': 'se', '%H': 'h', '%H%M': 'm', '%H%M%S': 'se'}
for p, u in time24_pat.items():
try:
ts = strftime('%H:%M:%S', strptime(ts, p))
break
except:
continue
sf = p
unit = time24_pat[sf] if unit is None else unit
if 'se' in unit.lower():
frm = sf if frm is None else frm
elif 'm' in unit.lower():
frm = sf if frm is None else frm
rnd = rnd * 60
elif 'h' in unit.lower():
frm = p if frm is None else frm
rnd = rnd * 3600
secs = sum(int(x) * 60 ** i for i, x in enumerate(reversed(ts.split(':'))))
rtm = int(round(secs / rnd, 0) * rnd)
nt = strftime(frm, gmtime(rtm))
return nt
Call function as follow:
Round to nearest 5 minutes with ouput format = hh:mm as follow
ts = '02:27:29'
nt = toNearestTime(ts, unit='min', rnd=5, frm='%H:%M')
print(nt)
output: '02:25'
Or round to nearest 30 minutes with ouput 12 hour format hh:mm:ss as follow
ts = '11:14PM'
nt = toNearestTime(ts, rnd=30, frm='%I:%M:%S %p')
print(nt)
output: '11:00:00 PM'
Or convert from 12 hour format to 24 hour format as follow
ts = '1:30:00 PM'
nt = toNearestTime(ts, frm='%H:%M:%S')
print(nt)
output: '13:30:00'