繁体   English   中英

我如何在python中按日期排序?

[英]How do i sort line by date in python?

我有这个 temp.txt 文件:

73.00   1   87  241531  02/06/19    1
95.00   1   87  244012  06/06/19    1
47.00   1   87  447     08/01/13    0
126.00  1   87  242697  08/06/19    1
106.00  1   87  242699  08/06/19    1
94.00   1   87  242293  09/06/19    1
192.00  1   87  242710  09/06/19    1
54.00   1   87  243243  13/06/19    1
106.00  1   87  243421  13/06/19    1

我想按日期对行进行排序。

这是我的代码(不起作用):

from datetime import datetime
import re


def func():

    temp_file = open("./temp.txt", "w")
    timestamp_regex = re.compile("[^:]+:\d\d:\d\d")

    def convert_time(logline):
        stamp = timestamp_regex.match(logline).group()  # this will error if there's no match.
        d = datetime.strptime(stamp, "%d/%m/%Y")
        return int(d.timestamp())

    temp_file_sorted_lines = sorted(open("./temp.txt", "r").readlines(), key=lambda line: line.split()[4])

    temp_file.close()

我究竟做错了什么? 如何正确排序线条?

这是使用datetimesorted一种方法

前任:

import datetime

with open(filename) as infile:
    data = sorted([line.split() for line in infile], key=lambda x: datetime.datetime.strptime(x[-2], "%d/%m/%y"))

print(data)

输出:

[['47.00', '1', '87', '447', '08/01/13', '0'],
 ['73.00', '1', '87', '241531', '02/06/19', '1'],
 ['95.00', '1', '87', '244012', '06/06/19', '1'],
 ['126.00', '1', '87', '242697', '08/06/19', '1'],
 ['106.00', '1', '87', '242699', '08/06/19', '1'],
 ['94.00', '1', '87', '242293', '09/06/19', '1'],
 ['192.00', '1', '87', '242710', '09/06/19', '1'],
 ['54.00', '1', '87', '243243', '13/06/19', '1'],
 ['106.00', '1', '87', '243421', '13/06/19', '1']]

你可以使用熊猫:

import pandas as pd
df=pd.read_csv('file.txt',header=None, sep='\s+')
df['tmp'] = pd.to_datetime(df[4])
df = df.sort_values('tmp')
df.drop('tmp',axis=1,inplace=True)
df.to_csv('file_new.txt',header=False, index=False,sep='\t')

在新文件中输出:

47.0    1   87  447 08/01/13    0
73.0    1   87  241531  02/06/19    1
95.0    1   87  244012  06/06/19    1
54.0    1   87  243243  13/06/19    1
106.0   1   87  243421  13/06/19    1
126.0   1   87  242697  08/06/19    1
106.0   1   87  242699  08/06/19    1
94.0    1   87  242293  09/06/19    1
192.0   1   87  242710  09/06/19    1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM