SQL Tutorial SQL Advanced SQL Database SQL References

MySQL TIME_FORMAT() Function



The MySQL TIME_FORMAT() function formats a time or datetime value as specified by a format mask. This function only formats the hours, minutes, seconds, and microseconds found in a time or datetime value.

Syntax

TIME_FORMAT(datetime, format_mask)

Parameters

datetime Required. Specify the time or datetime value to format.
format_mask Required. Specify the format to apply to the datetime. The following is a list of options for this parameter. It can be used in many combinations.

ValueDescription
%fMicroseconds (000000 to 999999)
%HHour (00 to 23 generally, but can be higher)
%hHour (00 to 12)
%IHour (00 to 12)
%iMinutes (00 to 59)
%pAM or PM
%rTime in 12 hour AM or PM format (hh:mm:ss AM/PM)
%SSeconds (00 to 59)
%sSeconds (00 to 59)
%TTime in 24 hour format (hh:mm:ss)

Return Value

Returns the formatted time or datetime value as specified by a format mask.

Example 1:

The example below shows the usage of TIME_FORMAT() function.

mysql> SELECT TIME_FORMAT('16:38:42', '%H %i %s');
Result: '16 38 42'

mysql> SELECT TIME_FORMAT('16:38:42', '%h:%i:%s %p');
Result: '04:38:42 PM'

mysql> SELECT TIME_FORMAT('16:38:42', '%h:%i %p');
Result: '04:38 PM'

mysql> SELECT TIME_FORMAT('16:38:42.000123', '%r');
Result: '04:38:42 PM'

mysql> SELECT TIME_FORMAT('16:38:42.000123', '%T');
Result: '16:38:42'

mysql> SELECT TIME_FORMAT('16:38:42.000123', '%f');
Result: '000123'

mysql> SELECT TIME_FORMAT('2018-08-18 16:38:42.000004', '%h:%i:%s.%f');
Result: '04:38:42.000004'

Example 2:

Consider a database table called Orders with the following records:

OrderQuantityPriceOrderTime
1001.582017-08-18 10:38:42
1201.612018-03-23 07:14:16
1251.782018-09-12 05:25:56
501.802019-01-16 11:52:05
2001.722020-02-06 09:31:34

In the query below, the TIME_FORMAT() function is used to format the datetime value of OrderTime column:

SELECT *, 
TIME_FORMAT(OrderTime, '%h:%i %p') AS TIME_FORMAT_Value
FROM Orders;

This will produce a result similar to:

OrderQuantityPriceOrderTimeTIME_FORMAT_Value
1001.582017-08-18 10:38:4210:38 AM
1201.612018-03-23 07:14:1607:14 AM
1251.782018-09-12 05:25:5605:25 AM
501.802019-01-16 11:52:0511:52 AM
2001.722020-02-06 09:31:3409:31 AM

❮ MySQL Functions