How could I convert the below column Time 1 from string to time eg: Time2
Time1
438
448
1815
1758
Time2
04:38
04:48
18:15
17:58
How could I convert the below column Time 1 from string to time eg: Time2
Time1
438
448
1815
1758
Time2
04:38
04:48
18:15
17:58
Try the datetime
library
>>> Time1 = ['438','448','1815','1758']
>>> Time2 = []
>>> import datetime
>>> for t in Time1:
... Time2.append(datetime.datetime.strptime(t,'%H%M').strftime('%H:%M'))
>>> print (Time2)
['04:38', '04:48', '18:15', '17:58']
To start, some of your time1 cases are not in the hhmm format: there are only three digits in 438, but this can be incorporated nonetheless.
import datetime
def convert_string_to_time(str):
if len(str) < 4:
return datetime.time(hour=int(str[0]), minute=int(str[1:3]))
else:
return datetime.time(hour=int(str[0:2]), minute=int(str[2:4]))
This will return a datetime.time object for each time string. If you want to have the time in the format hh:mm:ss use str(convert_string_to_time(your string here))
You can use formatted strings:
Time1 = ['438','448','1815','1758']
Time2 = [f'{t[:-2]}:{t[-2:]}' for t in Time1]
print(Time2)
Output:
['4:38', '4:48', '18:15', '17:58']