Python计算当前时间与指定时间间隔 datetime.time减运算报错如何解决
错误含义
你遇到的报错unsupported operand type(s) for -: 'datetime.time' and 'datetime.time',意思是Python不支持两个datetime.time类型的对象直接执行减法运算。
不能直接相减的原因
datetime.time仅代表单一的时刻,不包含任何日期信息,直接相减存在无法解决的逻辑歧义:比如23:00:00和01:00:00相减,既可以理解为同一天23点减1点得到22小时,也可以理解为当天23点减次日1点得到-2小时,Python标准库没有预设这类歧义的处理规则,因此没有给datetime.time类型实现减法运算的重载。
修复方案
你可以通过两种方式实现时间差计算:
方案1:使用datetime对象计算(推荐)
不要调用.time()方法拆分出时间部分,直接用带完整日期信息的datetime对象做减法,运算结果会直接返回timedelta类型的时间差:
import datetime as dt current_time = dt.datetime.now() FMT = '%H:%M:%S' t1 = '10:33:26' # 把指定时间补全为和当前时间同日期的datetime对象 t1_obj = dt.datetime.strptime(t1, FMT).replace( year=current_time.year, month=current_time.month, day=current_time.day ) tduration = current_time - t1_obj print(tduration)
方案2:转秒数计算(仅适用于当日时间差)
如果确认两个时间都属于同一天,可以把time对象统一转换成当日零点后的总秒数再做减法:
import datetime as dt current_time = dt.datetime.now().time() FMT = '%H:%M:%S' t1 = '10:33:26' t1_obj = dt.datetime.strptime(t1, FMT).time() current_total_sec = current_time.hour * 3600 + current_time.minute * 60 + current_time.second t1_total_sec = t1_obj.hour * 3600 + t1_obj.minute * 60 + t1_obj.second duration_sec = current_total_sec - t1_total_sec print(f"时间差为{duration_sec}秒")
内容的提问来源于stack exchange,提问作者user15926013
相关产品推荐
相关产品推荐

