| by YoungTimes | No comments

Python中如何实现日期字符串(datetimes)相减

在日志系统中每条日志前一般都会带上毫秒级的时间戳,为了统计某部分代码的耗时,我们需要将两个时间戳相减,从而得到耗时分布,指导我们针对性的优化代码实现。

时间戳的示例如下:

2015-08-10 19:33:27.653
2015-08-10 19:31:28.209

在Python中如何将这两个字符串的日期相减呢?

from datetime import datetime

d1 = datetime.strptime("2015-08-10 19:33:27.653", "%Y-%m-%d %H:%M:%S.%f")
d2 = datetime.strptime("2015-08-10 19:31:28.209", "%Y-%m-%d %H:%M:%S.%f")

print(d1 - d2)

程序输出:

0:01:59.444000

这个时间差值不够友好,要是能得到秒级的耗时就更加直接了,比如从A到B耗时0.1s,从B到C耗时0.8s等等。如何得到秒级的耗时呢?

from datetime import datetime
from datetime import timedelta

d1 = datetime.strptime("2015-08-10 19:33:27.653", "%Y-%m-%d %H:%M:%S.%f")
d2 = datetime.strptime("2015-08-10 19:31:28.209", "%Y-%m-%d %H:%M:%S.%f")

print(d1 - d2)

delta_time = timedelta.total_seconds(d1 - d2)

print("diff time in seconds is : {}s".format(delta_time))

程序输出:

0:01:59.444000
diff time in seconds is : 119.444s

参考材料

https://stackoverflow.com/questions/3096953/how-to-calculate-the-time-interval-between-two-time-strings

https://stackoverflow.com/questions/31929538/how-to-subtract-datetimes-timestamps-in-python/31929686

除非注明,否则均为[半杯茶的小酒杯]原创文章,转载必须以链接形式标明本文链接

本文链接:http://www.banbeichadexiaojiubei.com/index.php/2020/12/31/python%e4%b8%ad%e5%a6%82%e4%bd%95%e5%ae%9e%e7%8e%b0%e6%97%a5%e6%9c%9f%e5%ad%97%e7%ac%a6%e4%b8%b2datetimes%e7%9b%b8%e5%87%8f/