班上datetime.time不支持对象减法,其原因与它不支持对象比较的原因相同,即因为它的对象可能未定义其对象tzinfo属性:
时间与时间的比较,其中当 a 在时间上先于 b 时,a 被视为小于 b。如果一个比较对象是幼稚的,而另一个比较对象是已知的,则会引发 TypeError。如果两个比较对象都知道,并且具有相同的 tzinfo 属性,则忽略公共 tzinfo 属性并比较基准时间。如果两个比较数都知道并且具有不同的 tzinfo 属性,则首先通过减去它们的 UTC 偏移量(从 self.utcoffset() 获得)来调整比较数。为了阻止混合类型比较回退到按对象地址进行的默认比较,当时间对象与不同类型的对象进行比较时,除非比较是 == 或 !=,否则会引发 TypeError。后一种情况分别返回 False 或 True。
你应该使用datetime.datetime其中包括日期和时间。
如果这两个时间指的是一天,你可以告诉 python 日期是今天,用date.today()并将日期与时间结合起来datetime.combine.
Now that you have datetimes you can perform subtraction, this will return a datetime.timedelta instance, which the method total_seconds() that will return the number of seconds (it's a float
that includes the microseconds information). So multiply by 106 and you get the microseconds.
from datetime import datetime, date, time
x = time(9, 30, 30, 0)
y = time(9, 30, 31, 100000)
diff = datetime.combine(date.today(), y) - datetime.combine(date.today(), x)
print diff.total_seconds() * (10 ** 6) # 1100000.0
您也可以只使用 timedeltas:
from datetime import timedelta
x = timedelta(hours=9, minutes=30, seconds=30)
y = timedelta(hours=9, minutes=30, seconds=31, microseconds=100000)
print (y - x).total_seconds() * (10 ** 6) # 1100000.0