MySQL - TIME_TO_SEC() Function



The MySQL TIME_TO_SEC() function accepts a time value as an argument, converts it into seconds and returns the result as a numerical value. If the time value argument is either invalid or NULL, the return value is also NULL.

Note: This function differs from the SECOND() function, as it does not retrieve the seconds part from the time value; instead converts the time from hours/minutes to seconds.

Syntax

Following is the syntax of MySQL TIME_TO_SEC() function −

TIME_TO_SEC(time);

Parameters

This method accepts the time value to be converted to seconds as a parameter.

Return value

The function returns the time value converted to seconds as an integer.

Example

In the following query, we are using the MySQL TIME_TO_SEC() function to convert the given time value into seconds −

SELECT TIME_TO_SEC('19:45:22') As Result;

Output

This will produce the following result −

Result
71122

Example

Here, we are passing DATETIME value to this function and converting it into seconds −

SELECT TIME_TO_SEC('1987-3-12 12:35:58') As Result;

Output

Following is the output −

Result
45358

Example

In this example, we have created a table named ORDERS using the following CREATE TABLE query −

CREATE TABLE ORDERS (
   OID INT NOT NULL,
   DATE VARCHAR (20) NOT NULL,
   CUSTOMER_ID INT NOT NULL,
   AMOUNT DECIMAL (18, 2)
);

Now, insert the following records into the ORDERS table using the INSERT statement −

INSERT INTO ORDERS VALUES 
(102, '2009-10-08 00:00:00', 3, 3000.00),
(100, '2009-10-08 00:00:00', 3, 1500.00),
(101, '2009-11-20 00:00:00', 2, 1560.00),
(103, '2008-05-20 00:00:00', 4, 2060.00);

Execute the below query to fetch all the inserted records in the above-created table −

Select * From ORDERS;

Following is the ORDERS table −

OID DATE CUSTOMER_ID AMOUNT
102 2009-10-08 00:00:00 3 3000.00
100 2009-10-08 00:00:00 3 1500.00
101 2009-11-20 00:00:00 2 1560.00
103 2008-05-20 00:00:00 4 2060.00

Here, we are using the TIME_TO_SEC() function to convert the values in datetime values in DATE column to seconds −

SELECT OID, DATE, TIME_TO_SEC(DATE)
As Result From ORDERS;

Output

The output is displayed as follows −

OID DATE Result
102 2009-10-08 00:00:00 0
100 2009-10-08 00:00:00 0
101 2009-11-20 00:00:00 0
103 2008-05-20 00:00:00 0
Advertisements