0

I have a column in for stop_time 05:38 (MM:SS) but it is showing up as an object. is there a way to turn this to a time?

I tried using # perf_dfExtended['Stop_Time'] = pd.to_datetime(perf_dfExtended['Stop_Time'], format='%M:%S')

but then it adds a date to the output: 1900-01-01 00:05:38

  • 3
    Does this answer your question? [Pandas - convert strings to time without date](https://stackoverflow.com/questions/32375471/pandas-convert-strings-to-time-without-date) – Henry Ecker Apr 28 '21 at 18:40

2 Answers2

1

I guess what you're looking for is pd.to_timedelta (https://pandas.pydata.org/docs/reference/api/pandas.to_timedelta.html). to_datetime operation which will of course always try to create a date.

What you have to remember about though is that pd.to_timedelta could raise ValueError for your column, as it requires hh:mm:ss format. Try to use apply function on your column by adding '00:' by the beginning of arguments of your column (which I think are strings?), and then turn the column to timedelta. Could be something like:

pd.to_timedelta(perf_dfExtended['Stop_Time'].apply(lambda x: f'00:{x}'))
Rafa
  • 564
  • 4
  • 12
  • This is what I was looking for thank you. Is there a way to clip the results though so it doesnt show days and hours? my data will never go past minutes – Amir Rahimpour Apr 28 '21 at 19:20
  • Not according to my knowledge, sorry. Maybe you can have one column to perform analysis and calculations, and another for showing the data (original column)? – Rafa Apr 28 '21 at 19:36
1

This may work for you:

perf_dfExtended['Stop_Time'] = \
    pd.to_datetime(perf_dfExtended['Stop_Time'], format='%M:%S').dt.time

Output (with some additional examples)

0    00:05:38
1    00:10:17
2    00:23:45
jch
  • 3,600
  • 1
  • 15
  • 17