Your code crashes, but does not save the name, because name will be set to the name in the file, because you only store the days when you go, so you always see the last name.
You also add + 1, which does not seem to be correct, since you should not add or include the last day, since the person does not stay that night. Your code really outputs ('John', 32) correct name randomly, because it is the last in your example file, and the day off is 1.
Just keep an eye on the best, which include the name and day you go, using the days left as a measure, and return them at the end:
from datetime import datetime from csv import reader def longest_stay(fpath): with open(fpath,'r')as f_handle: mx,best = None, None for name, a_date, d_date in reader(f_handle,delimiter=" "): days = (datetime.strptime(d_date, "%m/%d") - datetime.strptime(a_date, "%m/%d")).days
Outout:
In [13]: cat test.txt Robin 01/11 01/15 Mike 02/10 02/12 John 01/15 02/15 In [14]: longest_stay("test.txt")
You need to use abs only if the format is not always in start-end format, but you should know that it could get the wrong output using the abs value if your dates were years.
source share