Open In App

Python – Time Strings to Seconds in Tuple List

Last Updated : 08 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given Minutes Strings, convert to total seconds in tuple list.

Input : test_list = [("5:12", "9:45"), ("12:34", ), ("10:40", )] 
Output : [(312, 585), (754, ), (640, )] 
Explanation : 5 * 60 + 12 = 312 for 5:12. 
Input : test_list = [("5:12", "9:45")] 
Output : [(312, 585)] 
Explanation : 5 * 60 + 12 = 312 for 5:12.

Method 1: Using loop + split()

In this, we separate the minute and second components using split() and perform mathematical computation to convert the value to required seconds, strings converted to integers using int().

Python3




# Python3 code to demonstrate working of
# Time Strings to Seconds in Tuple List
# Using loop + split()
 
# initializing list
test_list = [("5:12", "9:45"), ("12:34", "4:50"), ("10:40", )]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Dictionary
res = []
 
for sub in test_list:
    tup = tuple()
 
    # iterating each tuple
    for ele in sub:
 
        # perform conversion
        min, sec = ele.split(":")
        secs = 60 * int(min) + int(sec)
        tup += (secs, )
    res.append(tup)
 
# printing result
print("The corresponding seconds : " + str(res))


Output

The original list is : [('5:12', '9:45'), ('12:34', '4:50'), ('10:40', )]
The corresponding seconds : [(312, 585), (754, 290), (640, )]

Time Complexity: O(n2)

Auxiliary Space: O(n)

Method 2: Using loop + find()+slicing

Python3




# Python3 code to demonstrate working of
# Time Strings to Seconds in Tuple List
# Using loop + split()
 
# initializing list
test_list = [("5:12", "9:45"), ("12:34", "4:50"), ("10:40", )]
 
# printing original list
print("The original list is : " + str(test_list))
 
 
res = []
for i in test_list:
    y=[]
    for j in i:
        x=j.find(":")
        a=int(j[:x])*60
        b=int(j[x+1:])
        y.append(a+b)
    res.append(tuple(y))
         
# printing result
print("The corresponding seconds : " + str(res))


Output

The original list is : [('5:12', '9:45'), ('12:34', '4:50'), ('10:40',)]
The corresponding seconds : [(312, 585), (754, 290), (640,)]

Method 3: Using list comprehension + map() + lambda()

Use list comprehension with map() and lambda() functions to achieve the desired output.

Approach:

  1. Define a lambda function to convert the time string into seconds
  2. Use the map() function to apply the lambda function to each element of the tuple
  3. Use the list comprehension to convert the tuple into a tuple of integers representing seconds
  4. Append the tuple of integers to the result list
  5. Print the result

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Time Strings to Seconds in Tuple List
# Using list comprehension + map() + lambda()
 
# initializing list
test_list = [("5:12", "9:45"), ("12:34", "4:50"), ("10:40", )]
 
# printing original list
print("The original list is : " + str(test_list))
 
# define lambda function to convert time string into seconds
to_seconds = lambda t: 60 * int(t.split(":")[0]) + int(t.split(":")[1])
 
# using list comprehension + map() + lambda() to convert time strings to seconds
res = [tuple(map(to_seconds, sub)) for sub in test_list]
 
# printing result
print("The corresponding seconds : " + str(res))


Output

The original list is : [('5:12', '9:45'), ('12:34', '4:50'), ('10:40',)]
The corresponding seconds : [(312, 585), (754, 290), (640,)]

Time complexity: O(n^2) (where n is the length of the input list)
Auxiliary space: O(n) (where n is the length of the input list)

Method 4: Using a for loop and a helper function

Approach:

  1. Define a helper function time_to_seconds that takes a time string as input and returns the corresponding number of seconds.
  2. Initialize a list test_list with three tuples, each containing one or two time strings.
  3. Print the original list test_list.
  4. Initialize an empty list res to store the converted seconds.
  5. Use a for loop to iterate over each tuple in test_list.
  6. For each tuple, initialize an empty list sub_res to store the converted seconds.
  7. Use another for loop to iterate over each time string in the current tuple.
  8. Call the helper function time_to_seconds with the current time string as input and append the result to the sub_res list.
  9. Convert the sub_res list to a tuple and append it to the res list.
  10. Print the final result res.

Python3




# define a helper function to convert time string to seconds
def time_to_seconds(time_str):
    minutes, seconds = time_str.split(':')
    return int(minutes) * 60 + int(seconds)
 
 
# initializing list
test_list = [("5:12", "9:45"), ("12:34", "4:50"), ("10:40", )]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using for loop to convert time strings to seconds
res = []
for sub in test_list:
    sub_res = []
    for time_str in sub:
        sub_res.append(time_to_seconds(time_str))
    res.append(tuple(sub_res))
 
# printing result
print("The corresponding seconds : " + str(res))


Output

The original list is : [('5:12', '9:45'), ('12:34', '4:50'), ('10:40',)]
The corresponding seconds : [(312, 585), (754, 290), (640,)]

The time complexity of this approach is O(nm), where n is the number of tuples in the list and m is the maximum number of time strings in a tuple. 

The auxiliary space is O(nm) as well because a new list is created to store the converted seconds.

Method 5: Using list comprehension + map() + split()

  1. Define the time_to_seconds function as given in the problem statement.
  2. Initialize the list test_list as given in the problem statement.
  3. Use a list comprehension along with the map() function to convert time strings to seconds for each sub-list in test_list.
  4. Split each time string into minutes and seconds using the split() function.
  5. Return the result as a list of tuples, where each tuple contains the corresponding seconds for each time string in the sub-list.
  6. Print the resulting list.

Python3




# define a helper function to convert time string to seconds
 
def time_to_seconds(time_str):
    minutes, seconds = time_str.split(':')
    return int(minutes) * 60 + int(seconds)
 
 
# initializing list
test_list = [("5:12", "9:45"), ("12:34", "4:50"), ("10:40", )]
 
# using list comprehension + map() + split() to convert time strings to seconds
res = [tuple(map(time_to_seconds, sub)) for sub in test_list]
 
# printing result
print("The corresponding seconds : " + str(res))


Output

The corresponding seconds : [(312, 585), (754, 290), (640,)]

Time complexity: O(nm), where n is the number of sub-lists in test_list and m is the maximum number of time strings in a sub-list.
Auxiliary space: O(nm), where n is the number of sub-lists in test_list and m is the maximum number of time strings in a sub-list. This is because we are storing the result in a new list of tuples, which has the same size as test_list.

Method  7 : Using NumPy and datetime.timedelta()

  1. Import the NumPy module and the datetime module from the datetime library.
  2. Define a helper function called time_to_seconds that takes a time string as input.
  3. Inside the function, use NumPy’s np.datetime64() function to create a time object from the time string.
  4. Use datetime.timedelta() method to convert the time object to seconds.
  5. Return the seconds.
  6. Define a list called test_list that contains some time strings.
  7. Use a list comprehension to apply the time_to_seconds function to each element of the test_list.
  8. Print the result.

Python3




import numpy as np
from datetime import datetime, timedelta
 
# define a helper function to convert time string to seconds
def time_to_seconds(time_str):
   
    time_obj = datetime.strptime(time_str, '%M:%S')
    seconds = (time_obj - datetime(1900, 1, 1)).total_seconds()
    return int(seconds)
 
# initializing list
test_list = [("5:12", "9:45"), ("12:34", "4:50"), ("10:40", )]
 
# using list comprehension + map() + split() to
# convert time strings to seconds
res = [tuple(map(time_to_seconds, sub)) for sub in test_list]
 
# Printing result
print("The corresponding seconds : " + str(res))


OUTPUT : 
The corresponding seconds : [(312, 585), (754, 290), (640,)]

Time complexity: The time complexity of this method is O(n), where n is the length of the input list. 

Auxiliary space: The auxiliary space used by this method is O(n), where n is the length of the input list.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads