我正在尝试根据日期对列表进行排序。
名单:
[datareplay/upstream/20230911/2023-09-11/WIRE_ISSN.WIRE_CRTD_0057c620ea6040849da9bceb977e7332-2023-09-11-19-30-10-00445.txt, datareplay/upstream/20230911/2023-09-11/WIRE_ISSN.WIRE_CRTD_00e1cd4e425243bda8e09ee2b7b2334f-2023-09-11-19-30-02-00554.txt, datareplay/upstream/20230911/2023-09-11/WIRE_ISSN.WIRE_CRTD_021b63466ff6406d8b30b25bda63b49f-2023-09-11-19-30-21-00218.txt, datareplay/upstream/20230911/2023-09-11/WIRE_ISSN.WIRE_CRTD_049a681a00214155b7dab7c94c871341-2023-09-11-19-30-15-00036.txt, datareplay/upstream/20230911/2023-09-11/WIRE_ISSN.WIRE_CRTD_068e490f3b78453293e84bdfb49112ad-2023-09-11-19-30-14-00288.txt, datareplay/upstream/20230911/2023-09-11/WIRE_ISSN.WIRE_CRTD_0694fca541d0486689c6591b16cb1fbc-2023-09-11-19-30-14-00405.txt, datareplay/upstream/20230911/2023-09-11/WIRE_ISSN.WIRE_CRTD_0a8d4975741e4b088ead2bfd1edee1ad-2023-09-11-19-30-07-00188.txt]
我想要排序的部分是 - 2023-09-11-19-30-10-00445
任何指导我做的帮助都非常感谢。
Python 中的自定义排序方法可用于根据每个字符串中的日期部分(例如“2023-09-11-19-30-10-00445”)对字符串列表进行排序。
from datetime import datetime
# Your list of strings
file_list = [
"datareplay/upstream/20230911/2023-09-11/WIRE_ISSN.WIRE_CRTD_0057c620ea6040849da9bceb977e7332-2023-09-11-19-30-10-00445.txt",
"datareplay/upstream/20230911/2023-09-11/WIRE_ISSN.WIRE_CRTD_00e1cd4e425243bda8e09ee2b7b2334f-2023-09-11-19-30-02-00554.txt",
# ... (other entries)
]
# Define a custom sorting function that extracts the date section and converts it to a datetime object
def custom_sort_key(item):
date_section = item.split('-')[-7:]
date_str = "-".join(date_section)
return datetime.strptime(date_str, "%Y-%m-%d-%H-%M-%S-%f")
# Sort the list based on the custom sorting function
file_list.sort(key=custom_sort_key)
# Now, file_list is sorted based on the date section
for file_path in file_list:
print(file_path)