python - 你如何获得 Python 中两个时间对象之间的差异

标签 python datetime

我在 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。有什么想法吗?

最佳答案

类(class)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其中包括日期和时间。

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

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

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

您也可以只使用时间增量:

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

关于python - 你如何获得 Python 中两个时间对象之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25265379/

相关文章:

c# - 指定 DateTime.ToString ("o") 小数精度

python时区GMT转换

python - 如何为模型中的排序添加字段长度?

来自 csv 的 Python 热图

python - 从同时包含印地语和英语的文件中仅提取印地语文本

python - 在 Tkinter 中删除椭圆的轮廓?

python - Django 从数据库获取多个字段

c++ - 将文件的最后修改日期转换为字符串 C++

java - java日期什么时候崩溃?

javascript - 解析 date-fns 返回前一天的值