关于datetime:你如何在Python中获得两个时间对象之间的差异

How do you get the difference between two time objects in Python

我在Python中有两个datetime.time对象,例如,

1
2
>>> x = datetime.time(9,30,30,0)
>>> y = datetime.time(9,30,31,100000)

但是,当我像对datetime.datetime对象那样做(y-x)时,我收到以下错误:

1
2
3
4
Traceback (most recent call last):
  File"<pyshell#6>", line 1, in <module>
    y-x
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

我需要以微秒为单位得到y-x值,即在这种情况下它应该是1100000.任何想法?


datetime.time不支持对象减法,原因与它不支持对象比较的原因相同,即因为它的对象可能没有定义它们的tzinfo属性:

comparison of time to time, where a is considered less than b when a precedes b in time. If one comparand is naive and the other is aware, TypeError is raised. If both comparands are aware, and have the same tzinfo attribute, the common tzinfo attribute is ignored and the base times are compared. If both comparands are aware and have different tzinfo attributes, the comparands are first adjusted by subtracting their UTC offsets (obtained from self.utcoffset()). In order to stop mixed-type comparisons from falling back to the default comparison by object address, when a time object is compared to an object of a different type, TypeError is raised unless the comparison is == or !=. The latter cases return False or True, respectively.

您应该使用datetime.datetime,其中包括日期和时间。

如果两次引用一天,您可以告诉python日期是今天,使用date.today()并使用datetime.combine将日期与时间结合起来。

既然你有日期时间你可以执行减法,这将返回一个datetime.timedelta实例,方法total_seconds()将返回秒数(它是包含微秒信息的float)。 所以乘以106就可以得到微秒。

1
2
3
4
5
6
7
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:

1
2
3
4
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