2017-01-02 5 views
0

.txtファイルはdates.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 

これらを日付順に並べ替えるにはどうすればよいですか?私はかなりdatetimeと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") 
関連する問題