I have a CSV file that I create from an API response. I get it unsorted and the API response does not have a query parameter to sort the returned payload. The CSV looks like below, where column A has some device identifiers and column B has the configuration last sync of these devices. The time is represented in relative time as seen in the screenshot.
How can I naturally sort the CSV file to have the rows ordered in the following sequence seconds, minutes, hours, days, weeks, months, years, and Never?
I have tried to sort the entries using natsort but I didn't get what I am trying to achieve:
import csv
import os
from natsort import natsort, natsort_keygen
natsort_key = natsort_keygen(key=lambda k: k["last_sync"])
fieldnames = ["device", "last_sync"]
with open("Devices_161846.csv", "rt") as csvfile:
csvreader = csv.DictReader(f=csvfile, fieldnames=fieldnames)
next(csvreader)
identities = list(csvreader)
sorted_identities = natsort.natsorted(identities, key=natsort_key)
new_file, ext = os.path.splitext(csvfile.name)
with open(f"{new_file}_Sorted.{ext}", "wt") as f:
csvwriter = csv.DictWriter(f=f, fieldnames=fieldnames)
csvwriter.writeheader()
csvwriter.writerows(sorted_identities)
I expect to get the same result, but sorted from newest to oldest.

I would use
parsefrom dateparser as a sorting key, this way :Output (Devices_161846_Sorted.csv) :
Input used (Devices_161846.csv) :