Python – Time Strings to Seconds in Tuple List
Last Updated :
08 May, 2023
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
test_list = [( "5:12" , "9:45" ), ( "12:34" , "4:50" ), ( "10:40" , )]
print ( "The original list is : " + str (test_list))
res = []
for sub in test_list:
tup = tuple ()
for ele in sub:
min , sec = ele.split( ":" )
secs = 60 * int ( min ) + int (sec)
tup + = (secs, )
res.append(tup)
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
test_list = [( "5:12" , "9:45" ), ( "12:34" , "4:50" ), ( "10:40" , )]
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))
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:
- Define a lambda function to convert the time string into seconds
- Use the map() function to apply the lambda function to each element of the tuple
- Use the list comprehension to convert the tuple into a tuple of integers representing seconds
- Append the tuple of integers to the result list
- Print the result
Below is the implementation of the above approach:
Python3
test_list = [( "5:12" , "9:45" ), ( "12:34" , "4:50" ), ( "10:40" , )]
print ( "The original list is : " + str (test_list))
to_seconds = lambda t: 60 * int (t.split( ":" )[ 0 ]) + int (t.split( ":" )[ 1 ])
res = [ tuple ( map (to_seconds, sub)) for sub in test_list]
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:
- Define a helper function time_to_seconds that takes a time string as input and returns the corresponding number of seconds.
- Initialize a list test_list with three tuples, each containing one or two time strings.
- Print the original list test_list.
- Initialize an empty list res to store the converted seconds.
- Use a for loop to iterate over each tuple in test_list.
- For each tuple, initialize an empty list sub_res to store the converted seconds.
- Use another for loop to iterate over each time string in the current tuple.
- Call the helper function time_to_seconds with the current time string as input and append the result to the sub_res list.
- Convert the sub_res list to a tuple and append it to the res list.
- Print the final result res.
Python3
def time_to_seconds(time_str):
minutes, seconds = time_str.split( ':' )
return int (minutes) * 60 + int (seconds)
test_list = [( "5:12" , "9:45" ), ( "12:34" , "4:50" ), ( "10:40" , )]
print ( "The original list is : " + str (test_list))
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))
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()
- Define the time_to_seconds function as given in the problem statement.
- Initialize the list test_list as given in the problem statement.
- Use a list comprehension along with the map() function to convert time strings to seconds for each sub-list in test_list.
- Split each time string into minutes and seconds using the split() function.
- Return the result as a list of tuples, where each tuple contains the corresponding seconds for each time string in the sub-list.
- Print the resulting list.
Python3
def time_to_seconds(time_str):
minutes, seconds = time_str.split( ':' )
return int (minutes) * 60 + int (seconds)
test_list = [( "5:12" , "9:45" ), ( "12:34" , "4:50" ), ( "10:40" , )]
res = [ tuple ( map (time_to_seconds, sub)) for sub in test_list]
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()
- Import the NumPy module and the datetime module from the datetime library.
- Define a helper function called time_to_seconds that takes a time string as input.
- Inside the function, use NumPy’s np.datetime64() function to create a time object from the time string.
- Use datetime.timedelta() method to convert the time object to seconds.
- Return the seconds.
- Define a list called test_list that contains some time strings.
- Use a list comprehension to apply the time_to_seconds function to each element of the test_list.
- Print the result.
Python3
import numpy as np
from datetime import datetime, timedelta
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)
test_list = [( "5:12" , "9:45" ), ( "12:34" , "4:50" ), ( "10:40" , )]
res = [ tuple ( map (time_to_seconds, sub)) for sub in test_list]
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.
Similar Reads
Python - Convert String Records to Tuples Lists
Sometimes, while working with data, we can have problem in which we need to convert the data list which in string format to list of tuples. This can occur in domains in which we have cross type inputs. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + eval() The
7 min read
Python | Convert String to tuple list
Sometimes, while working with Python strings, we can have a problem in which we receive a tuple, list in the comma-separated string format, and have to convert to the tuple list. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + split() + replace() This is a br
5 min read
Python | List of tuples to String
Many times we can have a problem in which we need to perform interconversion between strings and in those cases, we can have a problem in which we need to convert a tuple list to raw, comma separated string. Let's discuss certain ways in which this task can be performed. Method #1: Using str() + str
8 min read
Python | Flatten Tuples List to String
Sometimes, while working with data, we can have a problem in which we need to perform interconversion of data. In this, we can have a problem of converting tuples list to a single String. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension + join() The
7 min read
Python | Convert tuple records to single string
Sometimes, while working with data, we can have a problem in which we have tuple records and we need to change it's to comma-separated strings. These can be data regarding names. This kind of problem has its application in the web development domain. Let's discuss certain ways in which this problem
6 min read
Python | Convert String to list of tuples
Sometimes, while working with data, we can have a problem in which we have a string list of data and we need to convert the same to list of records. This kind of problem can come when we deal with a lot of string data. Let's discuss certain ways in which this task can be performed. Method #1: Using
8 min read
Python | Convert string tuples to list tuples
Sometimes, while working with Python we can have a problem in which we have a list of records in form of tuples in stringified form and we desire to convert them to a list of tuples. This kind of problem can have its occurrence in the data science domain. Let's discuss certain ways in which this tas
4 min read
Convert String to Tuple - Python
When we want to break down a string into its individual characters and store each character as an element in a tuple, we can use the tuple() function directly on the string. Strings in Python are iterable, which means that when we pass a string to the tuple() function, it iterates over each characte
2 min read
Convert tuple to string in Python
The goal is to convert the elements of a tuple into a single string, with each element joined by a specific separator, such as a space or no separator at all. For example, in the tuple ('Learn', 'Python', 'Programming'), we aim to convert it into the string "Learn Python Programming". Let's explore
3 min read
Convert list of strings to list of tuples in Python
Sometimes we deal with different types of data types and we require to inter-convert from one data type to another hence interconversion is always a useful tool to have knowledge. This article deals with the converse case. Let's discuss certain ways in which this can be done in Python. Method 1: Con
5 min read