如何在Python中获取两个时间对象之间的差异

2023-11-27

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

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

但是,当我对 datetime.datetime 对象执行 (y-x) 操作时,出现以下错误:

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属性:

时间与时间的比较,其中当 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Python中获取两个时间对象之间的差异 的相关文章

随机推荐