【问题标题】:Way to take diff of timestamp in python在python中获取时间戳差异的方法
【发布时间】:2018-10-12 03:50:24
【问题描述】:

我正在尝试测量引导加载程序时序,其中我需要测量 SPL、U-Boot 和总时间(SPL + U-Boot)。我的 minicom 控制台日志条目如下所示

$ cat u-boot-2017-01 | grep -e 'U-Boot SPL 2017' -e 'U-Boot 2017.01' -e 'Starting kernel ...'
[2018-10-11 15:05:11.021] U-Boot SPL 2017.01-05786-ge0aa2fcb13 (Oct 10 2018 - 13:53:01)
[2018-10-11 15:05:11.294] U-Boot 2017.01-05786-ge0aa2fcb13 (Oct 10 2018 - 13:53:01 -0400)
[2018-10-11 15:05:12.706] Starting kernel ...

现在

SPL 启动时间为:第 1 行和第 2 行的时间戳差异(SPL 启动和 U-Boot 启动)
U-Boot 启动时间是:第 2 行的时间戳差异和 第 3 行(U-Boot 启动和启动内核)
总时间为:时间戳 第 1 行和第 3 行的差异。

我看到 python timedelta 支持年、月、日、小时、分钟、秒、微秒、毫秒,但不知道如何将此时间戳转换为 timedelta。我正在学习python,所以想在那里尝试一下。有人可以建议应该如何做。我必须对多个产品和多个版本的引导加载程序进行这些测量,所以脚本会很好。

【问题讨论】:

  • 您是在问如何计算2018-10-11 15:05:11.0212018-10-11 15:05:11.294 之间的差异?
  • 是的,它们之间的区别。

标签: python linux


【解决方案1】:

使用datetime.strptime 非常简单,只需确保使用正确的格式。

查看可用的指令here

from datetime import datetime

start_time = '2018-10-11 15:05:11.021'
end_time = '2018-10-11 15:05:11.294'

FORMAT = '%Y-%m-%d %H:%M:%S.%f'

print(datetime.strptime(end_time, FORMAT) - datetime.strptime(start_time, FORMAT))
# 0:00:00.273000

【讨论】:

  • %f 不是微秒而不是毫秒?我提到的时间戳中有毫秒。所以我需要使用其他格式吗?
猜你喜欢
  • 2019-04-20
  • 2021-08-18
  • 1970-01-01
  • 2011-06-13
  • 2012-02-28
  • 2013-05-18
  • 2014-05-04
  • 2012-06-03
  • 1970-01-01
相关资源
最近更新 更多