csv 基于相对时间的字典排序列表

jslywgbw  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(91)

我有一个CSV文件,我从一个API响应创建。我得到它未排序和API响应没有一个查询参数来排序返回的有效负载。CSV看起来像下面,其中列A有一些设备标识符和列B有这些设备的配置最后同步。时间表示在相对时间中看到的截图。


的数据
如何自然地对CSV文件进行排序,使行按以下顺序排序:secondsminuteshoursdaysweeksmonthsyearsNever
我尝试使用natsort对条目进行排序,但我没有得到我想要实现的目标:

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)

字符串
我希望得到相同的结果,但从最新到最旧排序。

dtcbnfnu

dtcbnfnu1#

我会使用parse from dateparser作为排序键,如下所示:

# pip install dateparser
import csv, datetime, dateparser

def parse(st):
    if st == "Never": return datetime.datetime.min
    else:
        if (dt:=dateparser.parse(st.replace("a few", "0"))):
            return dt
        else:
            return datetime.datetime.now()

header = ["device", "last_sync"]

with (
    open("/Devices_161846.csv", "r") as inpf,
    open("Devices_161846_Sorted.csv", "w", newline="") as outf
):
    reader = csv.DictReader(inpf, fieldnames=header)
    writer = csv.DictWriter(outf, fieldnames=header)
    
    writer.writeheader()
    writer.writerows(
        sorted(reader, key=lambda x: parse(x["last_sync"]), reverse=True)
    )

字符串
输出(Devices_161846_Sorted.csv):

device,last_sync
j,a few seconds ago
f,29 minutes ago
g,38 minutes ago
c,an hour ago
a,an hour ago
d,13 hours ago
h,a day ago
e,4 days ago
b,17 days ago
i,Never


使用的输入(Devices_161846.csv):

a,an hour ago
b,17 days ago
c,an hour ago
d,13 hours ago
e,4 days ago
f,29 minutes ago
g,38 minutes ago
h,a day ago
i,Never
j,a few seconds ago

相关问题