0

I've got the following code which errors and I'm not sure why.

from datetime import datetime
import os

Right_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print('Right now is ' + Right_now)

filename = 'sysdate.txt'

with open(filename,"r") as fin:
     last_date = fin.read()
     my_date = datetime.strptime(str(last_date), '%Y-%m-%d %H:%M:%S')
fin.close()

The file contains the following date format 2018-01-18 11:01:54

However I'm getting the following error message..

Right now is 2018-01-18 11:16:13
Traceback (most recent call last):
  File "test1.py", line 11, in <module>
    my_date = datetime.strptime(str(last_date), '%Y-%m-%d %H:%M:%S')
  File "/usr/lib64/python2.7/_strptime.py", line 328, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains:

Python version is 2.7.5

user2496011
  • 67
  • 3
  • 12

2 Answers2

0

Assuming you are interested only in the last date, if there are more than one, you need to modify your program to account for the empty string returned at the very end:

with open(filename,"r") as fin:
    last_date = fin.read().split('\n')[-2]
    my_date = datetime.strptime(last_date, '%Y-%m-%d %H:%M:%S')

Using .read() will read the whole file at once. The last element will be the empty string returned when the end of file is reached. You can read more about it in this post and in the documentation.

Your corrected program reads the file and splits it into lines based on the newline character after which it selects the pre-last element which is your target date. The remaining command runs successfully.

You don't need the .close() at the end - with open closes the file automatically,

As of Python 2.5, you can avoid having to call this method explicitly if you use the with statement. For example, the following code will automatically close f when the with block is exited:

as written in the documentation.

atru
  • 4,699
  • 2
  • 18
  • 19
  • It still errors. There will only ever be 1 line in the output file. Traceback (most recent call last): File "test1.py", line 12, in my_date = datetime.strptime(last_date, '%Y-%m-%d %H:%M:%S') File "/usr/lib64/python2.7/_strptime.py", line 328, in _strptime data_string[found.end():]) ValueError: unconverted data remains: – user2496011 Jan 18 '18 at 03:46
  • It works perfectly for me. Can you copy-paste your exact file? – atru Jan 18 '18 at 03:54
0

Your problem is the new line character.

I had written a very similar program, reading one date from each row in a text file, and got the same error message.

I solved it by using rstrip() to remove the newline in a similar fashion:

with open(filename,"r") as fin:
    last_date = fin.read()
    my_date = datetime.strptime(str.rstrip(last_date), '%Y-%m-%d %H:%M:%S')

Even though the manual does not state it explicitly rstrip() also removes newline characters.