Reputation: 468
I have continues time data list with min:sec.msec and it is like,
t=['10:44.7',...,'36:25.1',..,'59:59.9',..,'00:00.1',...,'18:01.2']
This includes min:sec.msec
but I need to convert all the data format to Hour:min: sec
. It means data should be,
t_converted=['12:10:45',...,'12:36:25',..,'13:00:00',..,'14:00:00',..,'14:18:01']
How can I do using python?
Upvotes: 0
Views: 235
Reputation: 52
A simple time conversion can be done with
t_converted = [datetime.strptime(_t, '%M:%S.%f').strftime('%H:%M:%S') for _t in t]
The apparent requirement for everything to be offset by 12 hours makes it more complex Firstly, the only way of knowing when to go from 12, 13 is for the next time to be less than the previous e.g. 59:59.9, 00:00.1 If you had 30:30.0 then 45:00.0 and they were meant to be 12:30:30 and 13:45:00 there is literally no way of knowing
From that assumption, this code works:
from datetime import datetime, timedelta
t=['10:44.7','36:25.1','59:59.9','00:00.1','00:00.0','18:01.2']
t_converted = []
i = 0
prev_dt = None
for _t in t:
dt = datetime.strptime(_t, '%M:%S.%f') + timedelta(hours=12+i)
if prev_dt is not None and prev_dt > dt:
i += 1
dt += timedelta(hours=1)
t_converted.append(dt.strftime("%H:%M:%S"))
prev_dt = dt
print(t_converted)
Upvotes: 1