Search code examples
pythonpandasstringweb-scrapingtimedelta

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


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


Solution

  • 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