0

I need to convert my column with records like 'hh:mm:ss' to float format in order to make further calculations.

In excel it is done in very simple way, you just multiply 'hh:mm:ss' by 24, but in Python it doesn't work out. I'm new to Python, need your help.

Any idea?

My Dataframe:

list = ['01:36:01', '00:02:18', '02:59:40', '04:16:30']

Here is what I need to achieve:

lst = [['01:36:01', 1.600], ['00:02:18', 0.038] , ['02:59:40', 2.994], ['04:16:30', 4.275]]
df = pd.DataFrame(lst, columns = ['Time', 'Float'])

print(df)
       Time     Float
0   01:36:01    1.600
1   00:02:18    0.038
2   02:59:40    2.994
3   04:16:30    4.275
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • 2
    Does this answer your question? [pandas - change time object to a float?](https://stackoverflow.com/questions/28353218/pandas-change-time-object-to-a-float) – some_programmer Jan 26 '21 at 08:14

2 Answers2

2

You can use below logic to find the time difference in seconds and then convert it into hours

import datetime as d
lis = ['01:36:01', '00:02:18', '02:59:40', '04:16:30']
start_dt = dt.datetime.strptime("00:00:00", '%H:%M:%S')
[float('{:0.3f}'.format((dt.datetime.strptime(time, '%H:%M:%S') - start_dt).seconds/3600)) for time in lis]

Output:

[1.6, 0.038, 2.994, 4.275]
mad_
  • 8,121
  • 2
  • 25
  • 40
0

Have you seen this post that looks like what you are trying to do.

https://stackoverflow.com/a/47043887/14982298

Allan Bond
  • 17
  • 1
  • 6