以微秒为单位的时差未按预期工作

时间:2019-03-25 22:04:58

标签: python

我正在尝试获取两个日期时间之间的差异,但我不知道为什么在尝试获取微秒时会得到0:

from dateutil.parser import parse

x = parse("2019-03-25T17:33:08.829-03:00")
y = parse("2019-03-25T18:07:08.829-03:00")

result = y - x
print(result.microseconds) // prints 0

已尝试: Python - time difference in milliseconds not working for mePython speed testing - Time Difference - milliseconds

没有运气。

我在这里做错了什么?

2 个答案:

答案 0 :(得分:5)

您链接的帖子中的

One of the answers说:

  

请注意,c.microseconds仅返回timedelta的微秒部分!出于计时目的,请始终使用c.total_seconds()

如果您想要微秒部分,您还期望什么?您两个日期的秒数的小数部分相等,因此两者之差为0。

否则,请使用result.total_seconds() * 1e6 + result.microseconds

答案 1 :(得分:2)

您没有计算以微秒为单位的差异。相反,您发现时差为34分钟,并要求该时差的微秒部分。时差为0:34:00。在此图中,除 分钟之外的所有其他部分均为0。

要查看此效果,请将以下简单的跟踪代码插入您的程序:

print(result, type(result))
print(x, type(x))
print(y, type(y))

输出:

2019-03-25 17:33:08.829000-03:00 <class 'datetime.datetime'>
2019-03-25 18:07:08.829000-03:00 <class 'datetime.datetime'>
0:34:00 <class 'datetime.timedelta'>

您需要使用 entire 时间增量并将其转换为微秒。现在您已经看到了问题,我敢打赌,您可以自己解决它。 :-)

相关问题