Python date formatting ValueError: unconverted data remains:

51 views Asked by At

I was just iterating over a log and trying to find the difference in timestamps, between logs. Below is my unit test code of the problem. Trying to understand why this is not being parsed in the format. Any help will be greatly appreciated.

#import datetime
#import pandas as pd
from datetime import datetime

string1 = "02-23-24 13:37:46 0006847636: MKAP: Download"
string2 = "02-23-24 11:33:26 0000352403: MKAP: Download"
           #%m-%d-%y %H:%M:%S %f
if __name__ == '__main__':
    print(string2[:28].strip())
    if string2[30:] == "MKAP: Download":
        print("True")
        dt1 = datetime.strptime(string1[:28], "%m-%d-%y %H:%M:%S %f")
        dt2 = datetime.strptime(string2[:28], "%m-%d-%y %H:%M:%S %f")
        delta = dt2 - dt1
        print("Test", delta)

    else:
        print("False")

Error:

"C:\Scripts\python.exe" "ScriptFilter/test1.py"
Traceback (most recent call last):
  File "ScriptFilter/test1.py", line 8, in <module>
    dt1 = datetime.strptime(str_dt1, "%m-%d-%y %H:%M:%S %f")
  File "lib\_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "Python37\lib\_strptime.py", line 362, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains: 7636
1

There are 1 answers

1
zlElo On

The format of the date stuff is not correct. Try this:

if __name__ == '__main__':
    print(string2[:28].strip())
    if string2[30:] == "MKAP: Download":
        print("True")
        dt1 = datetime.strptime(str(string1[:28]), "%m-%d-%y %H:%M:%S %f")  # Corrected format
        dt2 = datetime.strptime(string2[:28].strip(), "%m-%d-%y %H:%M:%S %f")  # Corrected format
        delta = dt2 - dt1
        print("Test", delta)
    else:
        print("False")