0

I am trying to convert a column with data like this: 1:38:17 or 36:21 to timedelta format. This column is extracted from a website and converted to a table using pandas.

df[' Chip Time'] = df[' Chip Time'].apply(pd.to_timedelta, errors='coerce')

This returns 0 days 01:38:17 but for rows with minutes and seconds (36:21) it returns NaT. I would like to have the time properly converted and remove the days part leaving only the time like this: 01:38:17.

I tried using the code below but it doesn't strip the days but it strips the time.

df[' Chip Time'] = pd.to_timedelta(df[' Chip Time'].dt.days, unit='d')

Please is there another method I can use in order to return a result like this 01:38:17.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • Welcome to Stack Overflow! Check out the [tour]. It'd help to provide a sample of the data and your desired output in Pandas format. See [How to make good reproducible pandas examples](/q/20109391/4518341). See also [mre]. For general tips, check out [ask]. – wjandrea Sep 04 '22 at 15:24

1 Answers1

1

I think you want to use pd.to_datetime instead of pd.to_timedelta:

df[' Chip Time'] = pd.to_datetime(df[' Chip Time'], format='%H:%M:%S').dt.time
Lukas Kuhn
  • 73
  • 1
  • 6
  • Thank you for responding, I received a traceback error --------------------------------------------------------------------------- During handling of the above exception, another exception occurred: ValueError Traceback (most recent call last) /usr/local/lib/python3.7/dist-packages/pandas/_libs/tslibs/strptime.pyx in pandas._libs.tslibs.strptime.array_strptime() ValueError: time data ' 36:21' does not match format '%H:%M:%S' (match) – Riyat Likita Sep 04 '22 at 15:23
  • This is due to having multiple different formats in your column. Run it with `pd.to_datetime(df[' Chip Time'], format='%H:%M:%S', errors="ignore").dt.time` first and then a second time with `pd.to_datetime(df[' Chip Time'], format='%M:%S', errors="ignore").dt.time`. See: https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html – Lukas Kuhn Sep 04 '22 at 15:28
  • Hi, I received this error AttributeError: Can only use .dt accessor with datetimelike values – Riyat Likita Sep 04 '22 at 18:56
  • `df[' Chip Time'] = pd.to_datetime(df[' Chip Time'], format='%H:%M:%S', errors="ignore")` then `df[' Chip Time'] = pd.to_datetime(df[' Chip Time'], format='%M:%S', errors="ignore")` then run `df[' Chip Time'] = df[' Chip Time'].dt.time` – Lukas Kuhn Sep 05 '22 at 06:25
  • I tried the code but it returns the same values instead of correcting them – Riyat Likita Sep 06 '22 at 10:59