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'
                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
                        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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With