Change h:mm:ss to hh:mm:ss

Viewed 814

i am working with python and i have a df as:

time
00:01:24
00:22:44
00:12:32
00:02:56

and i want to change it as

time
01:24:00
22:44:00
12:32:00
02:56:00

i first removed 00: from the column by using:

df['time'] = df['time'].str.strip('00:)

and then tried

df['time'] =pd.to_datetime(df['time'], format="%H:%M").dt.time

but is giving error as

ValueError: time data '1' does not match format '%H:%M' (match)

Eventually while striping 00: the column values are becoming

1:24
22:44
12:32
2:56

Can someone help me out.Thanks

3 Answers
df['time'] = pd.to_datetime(df.time, format="%S:%H:%M").dt.time
df

Output

    time
0   01:24:00
1   22:44:00
2   12:32:00
3   02:56:00

With your shown samples, please try following. Using str.replace function of Pandas.

df['time'].str.replace(r"^(\d{2}):(\d{2}):(\d{2})",r"\2:\3:\1")

Explanation: Working on DataFrame's time column and using .str.replace function to replace values. In matching portion using capturing group capability of function to create 3 capturing groups(where 1st one will have 1st 2 digits followed by colon, 2nd and 3rd one will also be same), then while substituting it interchanging their places to get the expected output.

Do a cast to datetime, change to required format.

import pandas as pd

pd.to_datetime(df['time'], format="%S:%H:%M").dt.strftime("%H:%M:%S")
Related