我如何对填充格式化日期的.txt文件进行排序

时间:2017-01-02 06:15:24

标签: python datetime

我有一个名为dates.txt的.txt文件。像这样的代码就像这样

insert into addrlookup (user_name, rsrc_id, primary_addr)
values(lower('10e359269010'),'3040','132');

我如何按日期按最旧到最新排序?我很确定你必须使用datetime和strptime函数。

1 个答案:

答案 0 :(得分:0)

from datetime import datetime as dt


def sortFile(infilepath, outfilepath, fmt):
    lines = []
    with open(infilepath) as infile:
        for line in infile:
            lines.append(dt.strptime(line, fmt))  # parse the time, and read in the file

    lines.sort()  # sort the datetime objects
    with open(outfilepath, 'w') as outfile:
        for line in lines:
            outfile.write(line.stftime(fmt))  # write out the datetime objects with the parsing format

现在,您可以这样称呼它:

sortFile('path/to/input', /path/to/output', "%a %b %d %H:%M:%S %z %Y\n")