0

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:

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
yaliga
  • 57
  • 3

2 Answers2

1

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')
Shiva
  • 2,627
  • 21
  • 33
1

The file presumably contains a newline character \n at the end, which is included in the return value of read().

You have to remove it from the timestamp before passing it to strptime, for example by using the rstrip method (see How can I remove a trailing newline?):

then = open("service.txt","r").read().rstrip()
mkrieger1
  • 19,194
  • 5
  • 54
  • 65