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.



Similar Reads

Python program to convert seconds into hours, minutes and seconds
Given an integer n (in seconds), convert it into hours, minutes and seconds. Examples: Input : 12345 Output : 3:25:45 Input : 3600 Output : 1:00:00 Approach #1 : Naive This approach is simply a naive approach to get the hours, minutes and seconds by simple mathematical calculations. C/C++ Code # Python Program to Convert seconds # into hours, minut
5 min read
Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read
Python Program to find tuple indices from other tuple list
Given Tuples list and search list consisting of tuples to search, our task is to write a Python Program to extract indices of matching tuples. Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]Output : [3, 1]Explanation : (3, 4) from search list is found on 3rd index on test_list, hence included in r
8 min read
Python Program to Merge tuple list by overlapping mid tuple
Given two lists that contain tuples as elements, the task is to write a Python program to accommodate tuples from the second list between consecutive tuples from the first list, after considering ranges present between both the consecutive tuples from the first list. Input : test_list1 = [(4, 8), (19, 22), (28, 30), (31, 50)], test_list2 = [(10, 12
11 min read
Python | Merge list of tuple into list by joining the strings
Sometimes, we are required to convert list of tuples into a list by joining two element of tuple by a special character. This is usually with the cases with character to string conversion. This type of task is usually required in the development domain to merge the names into one element. Let’s discuss certain ways in which this can be performed. L
6 min read
Python program to convert a list of strings with a delimiter to a list of tuple
Given a List containing strings with a particular delimiter. The task is to remove the delimiter and convert the string to the list of tuple. Examples: Input : test_list = ["1-2", "3-4-8-9"], K = "-" Output : [(1, 2), (3, 4, 8, 9)] Explanation : After splitting, 1-2 => (1, 2). Input : test_list = ["1*2", "3*4*8*9"], K = "*" Output : [(1, 2), (3,
7 min read
Python | Replace tuple according to Nth tuple element
Sometimes, while working with data, we might have a problem in which we need to replace the entry in which a particular entry of data is matching. This can be a matching phone no, id etc. This has it's application in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + enumerate() This task
8 min read
Python - Raise elements of tuple as power to another tuple
Sometimes, while working with records, we can have a problem in which we may need to perform exponentiation, i.e power of tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed. Method #1: Using zip() + generator expression The combination of above functions can be used to perform this
8 min read
Practice Tags :