简体   繁体   中英

Comparing items in a list

I have a text file containing due dates and dates when tasks were assigned and whether they were completed or not. I want to write a code that can go through the file and determine whether the tasks are overdue. Ive turned each line in the text file to a list and I'm trying to check if the due date is passed the current date and whether the part of the line that comments whether the task is completed is "No".

for line in rdfile:
    line.strip("\n")
    thetasks = line.split(", ")

The due date is the 2nd last item in the list and the No for specifying whether the task is completed is the last item in the list.

Assuming the line is:

Admin, Assign initial tasks, 14 Apr 2020, 02 Apr 2020, No

After using the code above I have a list containing the items in the line above separated by the comma and space.

Based on your sample and assuming the format of your lines stay the same, you could use this.

from datetime import datetime

line = "Admin, Assign initial tasks, 14 Apr 2020, 02 Apr 2020, No"
splitLine = line.split(',')
date_obj = datetime.strptime(splitLine[2].lstrip(), '%d %b %Y')
print(date_obj.strftime('%d-%m-%Y'))
yes_no = splitLine[4].lstrip()
print(yes_no)

This function will do the job:

from datetime import datetime

def is_overdue(task):
    splited_line = [elem.strip() for elem in task.split(",")]

    # Datetime object with current datetime
    now = datetime.now()

    # Datetime object with due datetime
    due_datetime = datetime.strptime(splited_line[-2], '%d %b %Y')

    # Boolean value representing task completion 
    is_finished = (splited_line[-1] != "No")

    return (not is_finished) and (due_datetime < now)


line = "Admin, Assign initial tasks, 14 Apr 2020, 02 Apr 2020, No"

print(is_overdue(line))
# True

The function will check the given line for 2 things:

  • If the task's due date is in the past: (due_datetime < now)
  • If the task is finished (I suppose, that everything else than "No" means, that the task is done here)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM