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

2024-05-12 20:47:41 发布

您现在位置: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

没有运气。你知道吗

我做错什么了?你知道吗


Tags: infromimportparsertimeparse时间差异
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'>

您需要获取整个时间增量并将其转换为微秒。既然你看到了问题,我敢打赌你能自己解决。:-)

One of the answers你链接的帖子说:

Be aware that c.microseconds only returns the microseconds portion of the timedelta! For timing purposes always use c.total_seconds().

如果你想要微秒的部分,你还期望什么?两个日期的秒数的小数部分相等,因此差值为0。你知道吗

否则,使用result.total_seconds() * 1e6 + result.microseconds。你知道吗

相关问题 更多 >