2017-01-02 32 views
0

我有一個名爲dates.txt的.txt文件。它有像這樣的代碼,就像這樣如何排序格式化日期的.txt文件

Fri Jan 31 05:51:59 +0000 2014 
Fri Jan 31 05:01:39 +0000 2014 
Thu Jan 30 14:31:21 +0000 2014 
Sat Feb 01 06:53:10 +0000 2014 

如何按日期排序這些日期由最舊到最新?我很肯定你必須使用日期時間和strptime函數。

回答

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")