You can supply your own function as the key
argument to determine how a list is sorted.
import os
def date_sort(filename):
abc, hms, ymd = filename.split('_')
return ymd + hms
filenames = os.listdir('logs')
filenames.sort(key=date_sort)
You could also use Python's datetime
class, but I don't think it's necessary for simply sorting values like this. All you need are the units of time in descending size: year, month, day, hour, minute, second.
For just getting the two most recent, you don't really need to sort the whole list, but you can still use this same key function for "sorting" a heap queue. (Here's another answer that gives a good example using heapq
.)
import os
import heapq
def date_sort(filename):
abc, hms, ymd = filename.split('_')
return ymd + hms
filenames = os.listdir('logs')
first, second = heapq.nlargest(2, filenames, key=date_sort)
If you decide you would like to use datetime
, you should get the same results by altering your sort function to return a datetime
object using datetime.strptime
:
from datetime import datetime
def date_sort(filename):
abc, hms, ymd = filename.split('_')
return datetime.strptime(hms + ymd, ''%H%M%S%y%m%d')
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…