MySQL TIME_FORMAT Function

MySQL TIME_FORMAT function is one of the Date Functions, which is useful to format the time value as per the given specifier. Let us see how to use this function to format the given time expression with an example. The basic syntax of the MySQL TIME_FORMAT Function is as shown below:

TIME_FORMAT(Time, Time_format_specifier);

MySQL TIME_FORMAT function Example

The following are the list examples for this time format function. These queries help you understand all the format specifiers that are available.

In this example, First, %f returns the Microseconds. Next, %H returns the hours in 24 hours (0 to 23), and %h returns the Hours Value in 12 hours (1 to 12).

SELECT TIME_FORMAT('23:15:59.123456', '%f');

SELECT TIME_FORMAT('23:15:59.123456', '%H');

SELECT TIME_FORMAT('23:15:59.123456', '%h');
MySQL TIME_FORMAT Function 1

Here, in this Time Format example, %l returns Hours in 12 hours (1 to 12). Next, %k returns the hours in 24 hours (0 to 23) and %i return minutes.

SELECT TIME_FORMAT('23:15:59.123456', '%l');

SELECT TIME_FORMAT('19:15:59.999888', '%k');

SELECT TIME_FORMAT('19:15:59.999888', '%i');
Example 2

In this Date method example, First, %s returns the Seconds value. Next, %l return time in 12 hours and %p returns AM or PM. Within the third MySQL statement, %T returns the 24 hours Time (HH:MM:SS) from a given Time expression.

SELECT TIME_FORMAT('19:15:59.999888', '%s');

SELECT TIME_FORMAT('19:15:59.999888', '%l %p');

SELECT TIME_FORMAT('19:15:59.999888', '%T %p');
MySQL TIME_FORMAT Example 3

In this example, we are combing all the formats available to format Time values in a single statement.

SELECT TIME_FORMAT('19:15:59.999888', '%H, %i, %s, %f, %T %p');

SELECT TIME_FORMAT('19:15:59.999888', '%H %i %s %f %T %p');

SELECT TIME_FORMAT('19:15:59.999888', '%H %i %s %p');
Example 4

Example 5

In this example, we show you how to use this MySQL Time_format function on table data. Here, we are formatting the HireDate column value.

SELECT EmpID, 
       FirstName,
       LastName,
       Occupation,
       Sales,
       HireDate,
       TIME_FORMAT(HireDate, '%H %i %s %f %T %p') AS 'Time Format Example'
FROM customer;
MySQL TIME_FORMAT Example 5