Search code examples
pythondatetimestrptime

Python and Strptime Difference When Variable Set or Read From File But Exact Same Value


Going for worlds worst title there but I can basically sum this weirdness up in one line.

This works fine:

dnow=datetime.datetime.now()
racetime = '2016-01-05 13:39:53.968000'
NewRaceTime = datetime.datetime.strptime(racetime, '%Y-%m-%d %H:%M:%S.%f')
timedifference = dnow - NewRaceTime

But when racetime is read from a file in that exact same format it won't work.

If I remove the racetime = '2016-01-05 13:39:53.968000' things start going sideways.

If I use:

print racetime

It returns exactly the same 2016-01-05 13:39:53.968000. I can't see any extra blank spaces or anything on the file or IDE. As far as I can see it is the exact same.

But even though there's no visible difference Python is finding something:

Traceback (most recent call last):
  File "C:/Users/Desktop/PycharmProjects/Project/Script.py", line 153, in <module>
    NewRaceTime = datetime.datetime.strptime(racetime, '%Y-%m-%d %H:%M:%S.%f')
  File "C:\Python27\lib\_strptime.py", line 328, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains: 

There is no difference in me setting

racetime = '2016-01-05 13:39:53.968000'

And leaving it as racetime is already read from the file. Unconverted data remains said white space or something to me but there doesn't seem to be any.

To add to the weirdness I've used pretty much the exact same thing with XML and it's worked fine. Read in the time setting it as .text from the XML and Python was able to compare it to the current time without a problem.

I can't wrap my head around this. It seems daft there has to be something stupid I'm missing but I'm out of ideas here.


Solution

  • You have a new line \n at the end of your file. You can strip it out like so:

    import datetime
    
    dnow = datetime.datetime.now()
    
    with open("test.txt", 'r') as f:
        racetime = f.read()
    racetime = racetime.rstrip()
    
    NewRaceTime = datetime.datetime.strptime(racetime, '%Y-%m-%d %H:%M:%S.%f')
    timedifference = dnow - NewRaceTime
    
    print racetime