Search code examples
pythonpython-3.xdatetimestrptime

Time comparison using strptime in Python


I want to execute further when the difference between now() and datetime in service.txt file is greater than 25 seconds for that I tried the below code, but got error.

service.txt:

2021-07-19 21:39:07.876953

Python code:

then = open("service.txt","r").read()
duration = datetime.datetime.now() - datetime.datetime.strptime(then, '%Y-%m-%d %H:%M:%S.%f')
if str(duration) > '0:00:25.0' :
    # do something

Error:

Traceback (most recent call last):
   File "D:\python_projects\test.py", line 41, in <module>
    duration = datetime.datetime.now() - datetime.datetime.strptime(then, '%Y-%m-%d %H:%M:%S.%f')
   File "C:\Python\lib\_strptime.py", line 565, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
   File "C:\Python\lib\_strptime.py", line 365, in _strptime
    data_string[found.end():]) ValueError: unconverted data remains:


Solution

  • Value of then is 2021-07-19 21:39:07.876953\n.
    Note the newline character at the end which you are not accounting for while using strptime.

    You can fix it either by

    1. replacing \n with '' in then
    then = open("service.txt","r").read().replace('\n', '')
    
    1. including \n in the date format string:
    datetime.datetime.strptime(then, '%Y-%m-%d %H:%M:%S.%f\n')