Convert mm:ss string to hh:mm:ss time format in Python

Question:

Screenshot of dataframe I am working on

I want to convert the values in df[‘Chip Time’] column which are string obj to timedelta64.

Have tried this….> df2[‘Chip Time’] = pd.to_timedelta(df2[‘Chip Time’])

BUT GETS Error message …> ValueError: expected hh:mm:ss format

Asked By: Chukwunonso Jide

||

Answers:

You can add 00: if string has only one : by Series.str.count with Series.mask:

df2 = pd.DataFrame({"Chip Time": ['10:04','1:45:23','23:12']})

s = df2['Chip Time'].mask(df2['Chip Time'].str.count(':').eq(1), '00:' + df2['Chip Time'])
#alternative:
s = np.where(df2['Chip Time'].str.count(':').eq(1), '00:', '') + df2['Chip Time']
print (s)
0    00:10:04
1     1:45:23
2    00:23:12
Name: Chip Time, dtype: object

df2['Chip Time'] = pd.to_timedelta(s)
print (df2)
        Chip Time
0 0 days 00:10:04
1 0 days 01:45:23
2 0 days 00:23:12
Answered By: jezrael

You can use a regex with str.replace to add '0:' on values matching 'x:x' only:

df2['Chip Time'] = pd.to_timedelta(df2['Chip Time']
                    .str.replace('^(d+:d+)$', r'0:1', regex=True)
                   )

Example output:

        Chip Time
0 0 days 00:16:48
1 0 days 01:07:51

Used input:

  Chip Time
0     16:48
1   1:07:51
Answered By: mozway