Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert 4-digit number into hours:minutes time format in pandas

I have a time in string format of 4-digits which is composed of hours and minutes. E.g., 1608 and need to be converted to => 16:08

The data is in the form of a pandas data frame and I tried:

     A    st_time
1    23   1608
2    12   1635
3    18   1654
4    38   1705

I tried using:

df.st_time.to_datetime().strftime('%h-%m') 

However, it throws an error.

AttributeError: 'Series' object has no attribute 'to_datetime'
like image 363
Natheer Alabsi Avatar asked Feb 05 '23 16:02

Natheer Alabsi


2 Answers

You need to use pd.to_datetime by passing the series df.st_time to it. Once you do, you can access the time component.

df.assign(newtime=pd.to_datetime(df.st_time, format='%H%M').dt.time)

    A  st_time   newtime
1  23     1608  16:08:00
2  12     1635  16:35:00
3  18     1654  16:54:00
4  38     1705  17:05:00

However, if you want a string back with the specified format.

df.assign(newtime=pd.to_datetime(df.st_time, format='%H%M').dt.strftime('%H:%M'))

    A  st_time newtime
1  23     1608   16:08
2  12     1635   16:35
3  18     1654   16:54
4  38     1705   17:05
like image 149
piRSquared Avatar answered Feb 07 '23 18:02

piRSquared


First cast numeric to string and then use indexing with str:

df.st_time = df.st_time.astype(str)
df.st_time = df.st_time.str[:2] + ':' + df.st_time.str[-2:]
print (df)
    A st_time
1  23   16:08
2  12   16:35
3  18   16:54
4  38   17:05
like image 45
jezrael Avatar answered Feb 07 '23 19:02

jezrael