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

2024-09-29 19:25:09 发布

您现在位置: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函数,但无法根据时间对整个数据进行排序。在

^{pr2}$

Tags: 数据re时间callsatareaprnc
2条回答

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

您可以使用^{} module更轻松地读取数据:

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

假设您的data.txt文件如下所示(我将其向右截断了一点):

457526373620277249 17644162 2014年4月19日星期六14:29:22+0000 0 457522541926842368 402127017 2014年4月19日星期六14:14:09+0000 0 457519476511350786 65713724 2014年4月19日星期六14:01:58+0000 0

我还假设这里是制表符分隔的。在

这将正确解析数据,将日期作为字符串转换为正确的^{}对象,然后使用^{}对这些对象进行排序:

示例:

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)

输出:

^{pr2}$

相关问题 更多 >

    热门问题