How to seperate list of hours:minutes:seconds in python?

Question:

Hello i would like to seperate a list that looks like this:

04:05:43.0
04:05:44.0
04:05:45.0
04:05:46.0
04:05:47.0
04:05:48.0
04:05:49.0
04:05:50.0
04:05:51.0
04:05:52.0
04:05:53.0
04:05:54.0
04:05:55.0
04:05:56.0
04:05:57.0
04:05:58.0
04:05:59.0
04:06:00.0
04:06:01.0
04:06:02.0
04:06:03.0
04:06:08.0

to 3 seperated lists with hours/minutes and seconds

Expected result:

hrs = [4, 4, 4, 4, 4, 4, ......]
mins = [5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,.... ]
secs = [1, 2, 3, 4, 5, 6,.....]
Asked By: Corleone

||

Answers:

This code does exactly what you want!

list_ = [
    '04:05:43.0',
    '04:05:44.0',
    '04:05:45.0'
]

# create 3 different lists, seperating hrs mins and secs
hrs = []
mins = []
secs = []

# loop through the list and split the strings into 3 different lists
for i in list_:
    hrs.append(int(i.split(':')[0]))
    mins.append(int(i.split(':')[1]))
    secs.append(int(i.split(':')[2].split('.')[0]))
Answered By: Raj Dave

You can use zip and str.split in a generator expression:

# the output will be tuples
hrs, mins, secs = zip(*((int(float(x)) for x in s.split(':')) for s in data))

Or for lists instead of tuples:

hrs, mins, secs = map(list, zip(*((int(float(x)) for x in s.split(':'))
                                  for s in data)))

Output:

# hrs
[4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]

# mins
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6]

# secs
[43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 0, 1, 2, 3, 8]
Answered By: mozway

It’s easy when data is in fixed format

lst = [
'04:05:43.0',
'04:05:44.0',
'04:05:45.0',
'04:05:46.0',
'04:05:47.0',
'04:05:48.0',
'04:05:49.0',
'04:05:50.0',
'04:05:51.0',
'04:05:52.0',
'04:05:53.0',
'04:05:54.0',
'04:05:55.0',
'04:05:56.0',
'04:05:57.0',
'04:05:58.0',
'04:05:59.0',
'04:06:00.0',
'04:06:01.0',
'04:06:02.0',
'04:06:03.0',
'04:06:08.0',
]
hrs  = [int(i[0:2]) for i in lst]
mins = [int(i[3:5]) for i in lst]
secs = [int(i[6:8]) for i in lst]
print( "hrs =", hrs)
print( "min =", mins)
print( "secs =", secs)

Output:

hrs= [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
min= [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6]
secs= [43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 0, 1, 2, 3, 8]
Answered By: user3435121
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.