MySQL - TIME() Function



The MySQL TIME() function is used to retrieve and return the time part of the given date time or time expression and returns the result in the form of a string.

A timestamp expression in MySQL is usually displayed in the form of 'YYYY-MM-DD HH:MM:SS' string. If this type (or any equivalent timestamp) is passed as an argument to this function, only 'HH:MM:SS' is retrieved as the result. But if the timestamp passed is invalid or NULL, the result is also obtained as NULL value.

Syntax

Following is the syntax of MySQL TIME() function −

TIME(expr);

Parameters

This method accepts the date-time or the time expression from which you need to extract the time as a parameter.

Return value

This function returns the time portion of the provided datetime expression as a time value.

Example

In the following query, we are using the MySQL TIME() function to extracts and returns the time part from the given date and time value −

SELECT TIME('2015-09-05 09:40:45.2300') As Result;

Output

This will produce the following result −

Result
09:40:45.2300

Example

Here, we are retrieving the time value from the current timestamp −

SELECT TIME(CURRENT_TIMESTAMP) As Result;

Output

Following is the output −

Result
10:51:24

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

Now, we use the MySQL TIME() function to extract the time part from all the datetime values in the DATE column of ORDERS table −

SELECT OID, DATE, TIME(DATE) As Time FROM ORDERS;

Output

The output is displayed as follows −

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