You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3计算长时间操作的datetime微秒时间差结果异常

问题原因及解决方案

你的问题出在对timedelta.microseconds属性的理解错误上:

  • timedelta对象的microseconds属性仅存储时间差中不足1秒的微秒部分(范围0-999999),并不是整个时间差的总微秒数。
  • 实际运行5小时的时间差,总微秒数是5*3600*1000000=18000000000,但microseconds只会提取最后不足1秒的那部分数值,也就是你看到的761716。

正确的总耗时计算方式

要获取完整的总微秒数,有两种方法:

  1. 使用total_seconds()方法转换:
print(duration.total_seconds() * 1_000_000)
  1. 手动换算所有时间单位:
total_microseconds = duration.days * 86400 * 1_000_000 + duration.seconds * 1_000_000 + duration.microseconds
print(total_microseconds)

替换原代码中的print(duration.microseconds)为上述任意一种,就能得到正确的总耗时微秒数。

内容的提问来源于stack exchange,提问作者cmgchess

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 20:05:23