利用时间字符串计算时间差

一个订单表,已知时间字符串,需要计算出两笔订单之间的时间差,并找出两笔订单中时间差最大的一个

import datetime

time1 = "20201222171220360"
time2 = "20201222171320120"
time3 = "20201222171400360"
time4 = "20201222171400820"
time5 = "20201222171500060"

t1 = datetime.datetime.strptime(time1, "%Y%m%d%H%M%S%f") #年月日时分秒微秒
t2 = datetime.datetime.strptime(time2, "%Y%m%d%H%M%S%f")
t3 = datetime.datetime.strptime(time3, "%Y%m%d%H%M%S%f")
t4 = datetime.datetime.strptime(time4, "%Y%m%d%H%M%S%f")
t5 = datetime.datetime.strptime(time5, "%Y%m%d%H%M%S%f")
diff1 = t2-t1
diff2 = t3-t2
diff3 = t4-t3
diff4 = t5-t4

time_list = [['diff1',diff1],['diff2',diff2],['diff3',diff3],['diff4',diff4]]
time_list.sort(key=lambda ele:ele[1],reverse=True)  #根据第二个元素排序
print(t1)
print(t2)
print(t3)
print(t4)
print(t5)
print(diff1)
print(diff2)
print(diff3)
print(diff4)
print(diff4.seconds, diff4.microseconds)  #打印时间差秒,微秒
print(time_list)

------------------------------------

2020-12-22 17:12:20.360000
2020-12-22 17:13:20.120000
2020-12-22 17:14:00.360000
2020-12-22 17:14:00.820000
2020-12-22 17:15:00.060000
0:00:59.760000
0:00:40.240000
0:00:00.460000
0:00:59.240000
59 240000
[['diff1', datetime.timedelta(seconds=59, microseconds=760000)], ['diff4', datetime.timedelta(seconds=59, microseconds=240000)], ['diff2', datetime.timedelta(seconds=40, microseconds=240000)], ['diff3', datetime.timedelta(microseconds=460000)]]

你可能感兴趣的:(Python,python,时间字符串)