I have this python
code where I am getting current time
. Now I want to round it off to nearest 60
minute mark so that if 8:20
then it round off to 8:00
but if its 8:31
then it should round off to 9:00
. Based on this SO answer i tried this but it gives me error:
def roundTime(dt=None, roundTo=60):
"""Round a datetime object to any time laps in seconds
dt : datetime.datetime object, default now.
roundTo : Closest number of seconds to round to, default 1 minute.
Author: Thierry Husson 2012 - Use it as you want but don't blame me.
"""
if dt == None : dt = datetime.datetime.now()
seconds = (dt.replace(tzinfo=None) - dt.min).seconds
rounding = (seconds+roundTo/2) // roundTo * roundTo
return dt + datetime.timedelta(0,rounding-seconds,-dt.microsecond)
def round_time():
td = datetime.datetime.time(datetime.datetime.now())
print(roundTime(td, roundTo=60 * 60))
The error I get is TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'
. How can resolve this error and round of the time? Also if there's a more easier way to achieve this please let me know?
Additional related question: Once I have the time rounded off I also want to find the time which is 3 hours after from the rounded off time. Does +
operation works here?