将datetime.time四舍五入到最接近的60分钟标记时出错

时间:2017-07-10 11:01:32

标签: python datetime

我有python代码,我得到current time。现在我想将它四舍五入到最接近的60分钟标记,这样如果8:20那么它会转到8:00但是如果它是8:31那么它应该四舍五入到9:00 1}}。基于this SO answer我试过这个,但它给了我错误:

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))

我得到的错误是TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'。怎么能解决这个错误和一轮时间?如果有更简单的方法来实现这一点,请告诉我?

其他相关问题:一旦我将时间四舍五入,我也想找到离开时间3小时后的时间。 +操作在这里有效吗?

2 个答案:

答案 0 :(得分:1)

datetime.datetime.time函数中取出round_time()并运行:

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

如果您还需要3个小时,可以使用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)

顺便说一下,在roundTime(dt=None, roundTo=60)中,您应该更改为以下代码,这样当您不发送dt时,您将获得当前小时的正确答案:

def roudTime(dt=None, roundTo = 60*60):

答案 1 :(得分:1)

如函数注释中所述:dt变量必须是datetime.datetime对象(不是datetime.time对象)。

def round_time():
    dt = datetime.datetime.now()
    dt_rounded = roundTime(dt, roundTo=60 * 60)
    time_rounded = dt_rounded.time()
    print(time_rounded)