SoFunction
Updated on 2024-10-30

Example of python converting hours, minutes and seconds to seconds

I encountered a problem when dealing with data, the data exported from the database is in the format of hours, minutes and seconds: hh:mm:ss , and now I need to convert it to seconds for easy calculation.

The original data may be divided into two cases, the field may be of text string type or time type, they are handled differently, so we discuss them separately.

1, string type conversion to seconds

You can calculate the number of seconds by separating them with ':' and deriving the hours, minutes and seconds respectively. So we define the following function:

def str2sec(x):
  '''
  String hours, minutes and seconds converted to seconds
  '''
  h, m, s = ().split(':') The #.split() function separates them by ':', and the .strip() function is used to remove spaces.
  return int(h)*3600 + int(m)*60 + int(s) #int()Functions converted to integer arithmetic

2. Conversion of time types to seconds

By itself, if the format is a time type, we can easily solve the problem using python's built-in datetime module by defining the following function:

def time2sec(y):
  '''
  Time type minutes, hours, minutes and seconds converted to seconds
  '''
  h =  # Use the module's built-in methods directly to get the hours, minutes, and seconds
  m = 
  s = 
  return int(h)*3600 + int(m)*60 + int(s) #int()Functions converted to integer arithmetic

First we import the data:

import pandas as pd
data = pd.read_excel(r"C:\Users\chih-cheng\Desktop\")
#Import data

#View data types

Run results:

It turns out that the "total hours worked" field is not a string type, so we use the second definition of the function to solve the problem, the code is as follows:

data['Total hours worked'] = data['Total hours worked'].apply(time2sec)
# Just apply the defined time2sec() function directly to the element
print(data)

The results are as follows:

Great job.

The above example of python converting hours, minutes and seconds to seconds is all that I have shared with you.