-1

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

Roshhh
  • 11
  • 1
  • Does this answer your question? [Parsing time string in Python](https://stackoverflow.com/questions/10494312/parsing-time-string-in-python) – mkrieger1 May 28 '20 at 17:28
  • Rather https://stackoverflow.com/questions/2265357/parse-date-string-and-change-format – mkrieger1 May 28 '20 at 17:29

3 Answers3

1

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']
Prateek Dewan
  • 1,411
  • 2
  • 16
  • 27
0

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']
Ann Zen
  • 17,892
  • 6
  • 20
  • 39
0

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))