I have the following list -
['ABC_20220816_21:50:07:UTC.pcap', 'ABC_20220816_17:05:23:UTC.pcap', 'ABC_20220816_18:06:10:UTC.pcap', 'ABC_20220816_17:10:23:UTC.pcap', 'ABC_20220816_16:45:05:UTC.pcap', 'ABC_20220816_19:07:30:UTC.pcap', 'ABC_20220816_21:19:08:UTC.pcap', 'ABC_20220816_19:37:48:UTC.pcap', 'ABC_20220816_20:13:31:UTC.pcap', 'ABC_20220816_18:27:29:UTC.pcap', 'ABC_20220816_19:32:48:UTC.pcap']
The format is the following - ABC_%Y%m%d_%H:%M:%S:UTC.pcap
I want to return a sorted list in ascending oder. I have tried the sort() and sorted() function. I have even tried using the datetime(in lambda function) module but I have no idea to get this to work. Can someone help me out here. Thank you.
CodePudding user response:
use:
import dateutil.parser as dparser
from datetime import datetime
a=['ABC_20220816_21:50:07:UTC.pcap', 'ABC_20220816_17:05:23:UTC.pcap', 'ABC_20220816_18:06:10:UTC.pcap', 'ABC_20220816_17:10:23:UTC.pcap', 'ABC_20220816_16:45:05:UTC.pcap', 'ABC_20220816_19:07:30:UTC.pcap', 'ABC_20220816_21:19:08:UTC.pcap', 'ABC_20220816_19:37:48:UTC.pcap', 'ABC_20220816_20:13:31:UTC.pcap', 'ABC_20220816_18:27:29:UTC.pcap', 'ABC_20220816_19:32:48:UTC.pcap']
b=sorted(a, key=lambda x: datetime.strptime(str(dparser.parse(x,fuzzy=True)), '%Y-%m-%d %H:%M:%S 00:00'))
print(b)
'''
['ABC_20220816_16:45:05:UTC.pcap', 'ABC_20220816_17:05:23:UTC.pcap', 'ABC_20220816_17:10:23:UTC.pcap', 'ABC_20220816_18:06:10:UTC.pcap', 'ABC_20220816_18:27:29:UTC.pcap', 'ABC_20220816_19:07:30:UTC.pcap', 'ABC_20220816_19:32:48:UTC.pcap', 'ABC_20220816_19:37:48:UTC.pcap', 'ABC_20220816_20:13:31:UTC.pcap', 'ABC_20220816_21:19:08:UTC.pcap', 'ABC_20220816_21:50:07:UTC.pcap']
'''