我的代码现在。
start = datetime.strptime(startDate, "%d/%m/%Y")
end = datetime.strptime(endDate,"%d/%m/%Y")
with open("filename.txt", "r") as f:
alldata = csv.reader(f, delimiter = "|")
for line in alldata:
alldataLine = datetime.strptime(line[0], "%d/%m/%Y")
if alldataLine >= start and alldataLine <= end :
print("{0} --> {1}".format(line[0], line[1]))
我的档案:
30/12/2015|3990.0
30/12/2015|6190.0
31/12/2015|12304.0
02/01/2016|12054.0
02/01/2016|8720.0
02/01/2016|18104.0
我想要的是,如果我有相同的约会,我希望我的节目在最后一个日期之后打印出来。
示例:
30/12/2015 - 31/12/2015
30/12/2015 --> 3990.0
30/12/2015 --> 6190.0
"one date"
31/12/2015 -->12304.0
"one date"
我尝试将第[0]行与第[0]行进行比较,但在每个日期之后都会打印“一个日期”。
答案 0 :(得分:0)
使用enumerate
并检查之前和之后的行:
with open("filename.txt", "r") as f:
alldata = f.readlines()
for i, line in enumerate(alldata):
alldataLine = datetime.strptime(line.split('|')[0], "%d/%m/%Y")
if alldataLine >= start and alldataLine <= end :
print("{0} --> {1}".format(line.split('|')[0], line.split('|')[1]))
try:
if line.split('|')[0] == alldata[i - 1].split('|')[0] and line.split('|')[0] != alldata[i + 1].split('|')[0]:
print("one date")
except IndexError:
pass