0

I have a dataframe containing different recorded times as string objects, such as 1:02:45, 51:11, 54:24.

I can't convert to time objects, this is the error I am getting:

"time data '49:49' does not match format '%H:%M:%S"

This is the code I am using:

df_plot2 = df[['year', 'gun_time', 'chip_time']]
df_plot2['gun_time'] = pd.to_datetime(df_plot2['gun_time'], format = '%H:%M:%S')
df_plot2['chip_time'] = pd.to_datetime(df_plot2['chip_time'], format = '%H:%M:%S')

Thanks in advance for your help!

2
  • Because 49:49 doesn't have the hour part? Looks like the proper format should be '%M:%S' for this? Commented Nov 30, 2021 at 20:07
  • Hi Daniel, could you add some sample data? The issue seems to come from the fact your data is not alsways formated the same. Commented Nov 30, 2021 at 20:12

2 Answers 2

1

you can create a common format in the time Series by checking string len and adding the hours as zero '00:' where there are only minutes and seconds. Then parse to datetime. Ex:

import pandas as pd

s = pd.Series(["1:02:45", "51:11", "54:24"])

m = s.str.len() <= 5
s.loc[m] = '00:' + s.loc[m]

dts = pd.to_datetime(s)
print(dts)
0   2021-12-01 01:02:45
1   2021-12-01 00:51:11
2   2021-12-01 00:54:24
dtype: datetime64[ns]
Sign up to request clarification or add additional context in comments.

Comments

0

I believe it may be because for %H python expects to see 01, 02, 03 etc instead of 1, 2, 3. To use your specific example 1:02:45 may have to be in the 01:02:45 format for python to be able to convert it to a datetime variable with %H:%M:$S.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.