使用datetime库在python中过滤时间数组

uinbv5nw  于 2021-09-08  发布在  Java
关注(0)|答案(3)|浏览(343)

我想在python datetime库的帮助下过滤我的时间字符串元素列表。
我有一个类似的数组-

time_Arr = ["0:0:16","3:59:9","2:50:32","23:46:52","20:30:12"]

我想让它从升序(0:0:0-23:59:59)中相应地过滤出来。
此外,我将有大量的数据(数组应该几乎包含超过5k的数据),那么什么是最有效的呢?
如何在python中实现这一点?
生成的数组应该类似于-

["0:0:16","2:50:32","3:59:9","20:30:12","23:46:52"]
kqqjbcuj

kqqjbcuj1#

这将把字符串转换为datetime,对它们进行排序,然后输出一个具有所需格式的列表。

from datetime import datetime
time_Arr = ["0:0:16","3:59:9","2:50:32","23:46:52","20:30:12"]
sorted(time_Arr, key=lambda x: datetime.strptime(x, '%H:%M:%S'))
``` `['0:0:16', '2:50:32', '3:59:9', '20:30:12', '23:46:52']` 
t9eec4r0

t9eec4r02#

使用datetime解析时间,然后进行排序:

from datetime import datetime
time_Arr = ["0:0:16","3:59:9","2:50:32","23:46:52","20:30:12"]
time_Arr = sorted([datetime.strptime(t, "%H:%M:%S") for t in time_Arr])

# [datetime.datetime(1900, 1, 1, 0, 0, 16),

# datetime.datetime(1900, 1, 1, 2, 50, 32),

# datetime.datetime(1900, 1, 1, 3, 59, 9),

# datetime.datetime(1900, 1, 1, 20, 30, 12),

# datetime.datetime(1900, 1, 1, 23, 46, 52)]
ctrmrzij

ctrmrzij3#

from datetime import datetime 
sorted([datetime.strptime(time, "%H:%M:%S") for time in time_Arr])

相关问题