gpt4 book ai didi

Python Dict() 根据日期时间排序

转载 作者:太空宇宙 更新时间:2023-11-04 10:16:33 25 4
gpt4 key购买 nike

我有一个文件有很多值,如下所示

{'Name':'xyz','Date':'Thu Jun 26 13:14:17 +0000 2008'}
{'Name':'xyz','Date':'Thu Jun 19 13:14:17 +0000 2009'}
{'Name':'xyz','Date':'Thu Jun 26 13:15:17 +0000 2008'}

如何根据日期和时间对这些值进行排序?

最佳答案

如果文件每行有一个,您需要转换为真正的 dict,例如使用 json.loadsast.literal_eval,然后排序:

import json
import datetime

def parse_date(datestr):
return datetime.datetime.strptime(datestr, '%a %b %m %H:%M:%S %z %Y')

with open(myfilename) as f:
mydicts = map(json.loads, filter(str.strip, f))
# This sorts on date value, but leaves them as original str
# in dict, can convert ahead of time if you want, or not, as you please
sorteddicts = sorted(mydicts, key=lambda d: parse_date(d['Date'])]

关于Python Dict() 根据日期时间排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35098973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com