0

I am reading a line from a text file. It contains the date in YYYY-MM-DD format. I am trying to convert it to datetime object so as to find the difference between two dates.

l = datetime.strptime(last_execution_date,"%Y-%m-%d").date()

Its throwing an error:ValueError: unconverted data remains:

But when I am using below its working perfectly fine

l = datetime.strptime('2019-01-25',"%Y-%m-%d").date()

My complete code looks something like this:

def incoming_mails_duration():
   f = open('last_script_execution_time.txt', 'r')
   last_execution_date = f.readline()
   print(last_execution_date)
   print(type(last_execution_date))
   l = datetime.strptime(last_execution_date,"%Y-%m-%d").date()
   print(l)
   print(type(l))
   present_date = date.today()
   delta_days = abs((present_date - l).days)
   f.close()

Why I am getting the above error when I am passing the string as variable read from a file ?

1 Answer 1

1

It is because f.readline() returns string with \n in the end. You either have to strip the newline character or include it inside strptime format argument.

Solution 1:

last_execution_date = f.readline().strip()

Solution 2:

l = datetime.strptime(last_execution_date,"%Y-%m-%d\n").date() # Note \n

Note

Also it is good practice to open files with with statement. This is a safe way to handle files. File will be safely closed even if exception occurred inside with block.

with open(filepath) as f:
    for line in f:
        # Work with line here
        pass
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.