Marta Marta - 1 month ago 9
Python Question

ValueError: time data ' 1:00:00' does not match format '%H:%M:%S'

I'm trying to convert a string to 'datetime64[ns]' format. The hours are non-zero-padded, which I guess may cause the problem.

Example of data:

1 8:49:15
2 8:49:16
3 8:49:17
Name: time, dtype: object


The code that I use to convert the string to time:

dfp['time'] = pd.to_datetime(dfp['time'], format='%H:%M:%S')


I also tried:

time_tansformed = []

for t in dfp['time']:
time_i = datetime.datetime.strptime(t, "%H:%M:%S")
time_tansformed.append(time_i)


and I got the same error:

ValueError: time data ' 1:00:00' does not match format '%H:%M:%S' (match)


I use Python 3.5 (Anaconda) on Win10.

How to convert it to time format?
Should I add 0 to pad the hours or is there a different way?

Answer

There's a leading space in the string:

' 1:00:00'

Do this:

dfp['time'] = pd.to_datetime(dfp['time'].strip(), format='%H:%M:%S')