我有一个包含如此多值的文件,如下所示
{'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'}
如何根据日期和时间对这些值进行排序?
答案 0 :(得分:2)
如果文件每行有这一个,则需要转换为真实的dict
,例如使用json.loads
或ast.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'])]
答案 1 :(得分:2)
您可以使用dateutil.parser
解析日期,并在key
函数中添加正确的sort
。
这有效 -
In [20]: from dateutil.parser import parse
In [21]: l = [{'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'}]
In [22]: sorted(l, key=lambda x: parse(x['Date']))
Out[22]:
[{'Date': 'Thu Jun 26 13:14:17 +0000 2008', 'Name': 'xyz'},
{'Date': 'Thu Jun 26 13:15:17 +0000 2008', 'Name': 'xyz'},
{'Date': 'Thu Jun 19 13:14:17 +0000 2009', 'Name': 'xyz'}]
答案 2 :(得分:0)
您可以使用stdlib中的email
包将日期格式解析为“自纪元以来的秒数”:
>>> from email.utils import parsedate_tz, mktime_tz
>>> mktime_tz(parsedate_tz('Thu Jun 26 13:14:17 +0000 2008'))
1214486057
很容易按dict
字段对Date
进行排序:
>>> sorted(dicts, key=lambda d: mktime_tz(parsedate_tz(d['Date'])))
[{'Date': 'Thu Jun 26 13:14:17 +0000 2008', 'Name': 'xyz'},
{'Date': 'Thu Jun 26 13:15:17 +0000 2008', 'Name': 'xyz'},
{'Date': 'Thu Jun 19 13:14:17 +0000 2009', 'Name': 'xyz'}]
要从文件加载json对象,可以使用code from @ShadowRanger's answer。