简体   繁体   中英

How to sort dates from a list using Python

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

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']

如果重新排序,首先是年份,然后是月份,然后是日期,那么基于字符串的排序应该会按预期工作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM