简体   繁体   中英

how to order dates from most recent to least recent

So here is this the code I use to insert into the tkinter listbox of downloaded files from the downloads folder to list all.zip files. How would I be able to make sure it orders the files from most recent to least recent?

for line in downloads:
            unixtime = os.stat(line).st_mtime
            kws = datetime.fromtimestamp(unixtime)
            if ".zip" in line:
                list.insert(tk.END, str(line), "Date modified: ", kws.date(), "\n")

using pathlib : eg

from pathlib import Path

src = Path('/your_downloads_directory')

zipfiles_sorted = sorted(src.glob('*.zip'), key=lambda p: p.lstat().st_mtime)

You can sort the downloads list first based on the modification time in reverse order:

downloads = sorted(((os.stat(line).st_mtime, line) for line in downloads if line.endswith('.zip')), reverse=1)
for unixtime, line in downloads:
    kws = datetime.fromtimestamp(unixtime)
    listbox.insert(tk.END, line, 'Date modified:', kws.date())

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