gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:40:21 25 4
gpt4 key购买 nike

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

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

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

这将正确解析数据,将日期作为字符串转换为正确的 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']
>>>

关于python - python中如何根据日期对数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30819200/

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