Search code examples
pythonpython-2.7datetimetext-processingstrptime

Calculate Time Difference between time in text file and now


I am new to Python and am writing a simple script to calculate the time difference between a time written to a text file and now. The format of the time in the text file is: 2013-10-05 00:20

This is the script

f = open('N:\\newfile.txt')
timestamp = f.readline()
f.close()
now = str(datetime.now())
#Removing the seconds from the now time
now = now[0:16]
FMT = '%Y-%m-%d %H:%M'
tdelta = datetime.strptime(now, FMT) - datetime.strptime(timestamp, FMT)
print tdelta

But when I run it I get the following error

Traceback (most recent call last):
File "N:\Test.py", line 12, in <module>
tdelta = datetime.strptime(now, FMT) - datetime.strptime(timestamp, FMT)
File "C:\Program Files (x86)\Python26\lib\_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains:

Can anyone please suggest what I am doing wrong?


Solution

  • The readline() method of file objects returns a line including it's terminating newline. Python's documentation has the details:

    f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline.

    So, your timestamp looks something like this:

    '2014-06-18 23:33\n'
    

    ... and strptime() is choking on that final newline. You can fix it by changing this line:

    timestamp = f.readline()
    

    to

    timestamp = f.readline().strip()
    

    (using the str.strip() method to strip whitespace from the string).