如何将列表中的下一个日期时间与当前日期时间进行比较

时间:2015-01-20 11:16:03

标签: python datetime

import os  
from datetime import datetime  

InFileName = r'path\Snapshot_list.txt'
#OutFileName = r'path\Process.bat'

InFile = open(InFileName)
for line in InFile:

s='20'
line = s[:2] + line[2:] [:6]
datetimeobject = datetime.strptime(line,'%Y%m%d')
newformat = datetimeobject.strftime('%Y-%m-%d')

print (newformat)

InFile.close()

我得到的格式是:

2012-05-30
2012-05-31
2012-06-01
2012-06-02
2012-06-03
2012-06-05

我想将每一行与之前的行进行比较,如果第2行!=第1行+ 1那么我会写出事情'在outfile中

1 个答案:

答案 0 :(得分:1)

from datetime import timedelta    

prev_date= None
for line in InFile:
    datetimeobject = datetime.strptime(line,'%Y%m%d')
    if datetimeobject-timedelta(days=1) != prev_date:
        outfile.write('things')
    prev_date= datetimeobject