MySQL TIME_FORMAT Function

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

TIME_FORMAT(Time, Time_format_specifier);

MySQL TIME_FORMAT function Example 1

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

In this example, First, %f returns the Microseconds. Next, %H returns the hours in 24 hours format (0 to 23), and %h returns the Hours Value in 12 hours format (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 MySQL Time Format example, %l returns Hours in 12 hours format (1 to 12). Next, %k returns the hours in 24 hours format (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');
MySQL TIME_FORMAT Function 2

In this Date Function example, First, %s returns the Seconds value. Next, %l return time in 12 hours format 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 Function 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');
MySQL TIME_FORMAT Function 4

MySQL TIME_FORMAT Example 2

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 `MySQL Tutorial`.customer;
MySQL TIME_FORMAT Function 5