Search code examples
pythondatereadlinesexternal-data-source

Checking if date is overdue from text file


I have a text file that has users and then due dates. I would like to be able to read the due date which was initially input by the user and see if the date is overdue compared with the current date. Any help would be appreciated.

Text file:

User: Tommy

Gender: Male

Date due: 2020-02-18

The code I have so far is:

import datetime
data = open("duedate.txt", "r")
    d = datetime.datetime.today()
    line = data.readlines(3)
    if line > d
        print("This date is overdue ") 

Solution

  • Try this:

    import datetime
    today = datetime.datetime.today()
    with open("duedate.txt", "r") as f:
        for line in f:
            if not line.startswith('Date due'): continue
            field, value = line.split(':')
            if field == 'Date due':
                if datetime.datetime.strptime(value.strip(), '%Y-%m-%d') < today:
                    print("Overdue")