0

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?

Community
  • 1
  • 1
user2966197
  • 2,793
  • 10
  • 45
  • 77

2 Answers2

1

Take out datetime.datetime.time in round_time() function and it works:

def round_time():
    td = datetime.datetime.now()
    res = roundTime(td, roundTo=60 * 60).time()
    print(res)

If you want 3 more hours you can use timedelta:

def round_time():
    td = datetime.datetime.now() + datetime.timedelta(hours=3) // plus 3 more hours
    res = roundTime(td, roundTo=60 * 60).time()
    print(res)

By the way, in roundTime(dt=None, roundTo=60) you should change to below code so you will get correct answer for current hour when you don't send in dt:

def roudTime(dt=None, roundTo = 60*60):
gaback
  • 638
  • 1
  • 6
  • 13
1

As described in the function comment: the dt variable must be a datetime.datetime object (not a datetime.time object).

def round_time():
    dt = datetime.datetime.now()
    dt_rounded = roundTime(dt, roundTo=60 * 60)
    time_rounded = dt_rounded.time()
    print(time_rounded)
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103