如何在 Python 中根据日期对数据进行排序



>我有一个以下格式的输入文件:

457526373620277249  17644162    Sat Apr 19 14:29:22 +0000 2014  0   nc  nc  U are expressing a wish not a fact ;) @Manicdj99 @ANTIVICTORIA @Nupe117 @cspanwj
457522541926842368  402127017   Sat Apr 19 14:14:09 +0000 2014  0   nc  nc  @dfwlibrarian You're a great one to call somebody else "educationally challenged!" I'd call that a name call. #YouLose #PJNET #TCOT #TGDNGO YouLose,PJNET,TCOT,TGDNGO
457519476511350786  65713724    Sat Apr 19 14:01:58 +0000 2014  0   nc  nc  @Manicdj99 @Nupe117 @cspanwj only some RW fringies are upset- & they're ALWAYS angry at something-also too fat 2 get out of lazyboys

我需要根据时间对数据进行排序。我正在使用strptime函数,但无法根据时间对整个数据进行排序。

import datetime
dt=[]
for line in f:
    splits = line.split('t')
    dt.append(datetime.datetime.strptime(splits[2], "%a %b %d %H:%M:%S +0000 %Y"))
    dt.sort()

假设你的data.txt文件看起来像这样(我把它截断了一点到右边):

457526373620277249 17644162 周六 4月 19 日 14:29:22 +0000 2014 0457522541926842368 402127017 周六 4 月 19 日 14:14:09 +0000 2014 0457519476511350786 65713724 周六 4月 19 14:01:58 +0000 2014 0

我还假设它在这里是 TAB 分隔的。

这将正确解析数据,将日期作为字符串转换为正确的datetime对象,然后可以使用sorted(iterable, key=)进行排序:

例:

from __future__ import print_function

from datetime import datetime
from operator import itemgetter

def map_to_datetime(xs, index, format="%a %b %d %H:%M:%S +0000 %Y"):
    for x in xs:
        x[index] = datetime.strptime(x[index], format)

data = [line.split("t") for line in map(str.strip, open("data.txt", "r"))]
map_to_datetime(data, 2)
for entry in sorted(data, key=itemgetter(2)):
    print(entry)

输出:

$ python -i foo.py
['457519476511350786', '65713724', datetime.datetime(2014, 4, 19, 14, 1, 58), '0']
['457522541926842368', '402127017', datetime.datetime(2014, 4, 19, 14, 14, 9), '0']
['457526373620277249', '17644162', datetime.datetime(2014, 4, 19, 14, 29, 22), '0']
>>> 

您希望生成行列表,然后才对整个列表进行排序;您只捕获时间戳,并在每次添加新时间戳时对该列表进行排序,忽略其余数据。

您可以使用csv模块更轻松地读取数据:

import csv
from datetime import datetime
from operator import itemgetter
rows = []
with open(yourfile, 'rb') as f:
    reader = csv.reader(f, delimiter='t')
    for row in reader:
        row[2] = datetime.strptime(row[2], "%a %b %d %H:%M:%S +0000 %Y")
        rows.append(row)
rows.sort(key=itemgetter(2))  # sort by the datetime column

相关内容

  • 没有找到相关文章

最新更新