Reputation: 615
This list is organized by day.month.year
. Before my list was a prefix. For example:
[Objname].01.02.2020.log
. I used a regex (\[Obj.*]).(\d{2}.\d{2}.\d{4})
for splitting the ObjectName from date. This is the resulted:
01.02.2020
02.02.2020
03.02.2020
04.02.2020
05.02.2020
06.02.2020
07.02.2020
08.02.2020
09.02.2020
10.02.2020
11.02.2020
12.02.2020
13.02.2020
14.02.2020
15.02.2020
16.02.2020
17.02.2020
18.02.2020
19.02.2020
20.02.2020
21.02.2020
22.02.2020
23.02.2020
24.02.2020
25.02.2020
26.02.2020
27.02.2020
29.01.2020
30.01.2020
31.01.2020
I used sorted()
because the Objectname is composite by numbers and I needed return this files sorted. But I don't know how is the best way to handle with this.
def getFiles(numbers):
currentDay = datetime.datetime.now()
numdays = numbers
dateList = []
for x in range (0, numdays):
date = currentDay - datetime.timedelta(days = x)
days = date.strftime("%d.%m.%Y")
dateList.append(days)
path = "/var/log/"
files = sorted([filename for root, dirs, files in os.walk(path)
for filename in files
for date in dateList
if filename.endswith(date+".log")])
return files
Upvotes: 0
Views: 43
Reputation: 51152
Your dates are in dd.mm.yyyy
order, and you want to sort them in yyyy.mm.dd
order; so you can use a key
function which splits on .
and reverses the components.
>>> date_strings = ['01.01.2009', '04.07.2007', '05.06.2007', '06.06.2007']
>>> sorted(date_strings, key=lambda d: d.split('.')[::-1])
['05.06.2007', '06.06.2007', '04.07.2007', '01.01.2009']
Upvotes: 4
Reputation: 6109
If you reorder it so that the year is first, then the month, then the day, string-based sorting should work as expected.
Upvotes: 0