MySQL TIME_FORMAT() Function
MySQL TIME_FORMAT() Function
The MySQL TIME_FORMAT() function formats a TIME or DATETIME value according to a format template string. It works like DATE_FORMAT(), except it accepts only time-related format specifiers.
Use TIME_FORMAT() when reports need 12-hour clocks with AM/PM ('02:30 PM'), compact durations ('14h 05m'), or microsecond labels. It returns a formatted string (VARCHAR), not a sortable TIME value.
Because TIME_FORMAT() supports TIME durations over 24 hours, %H prints values like '36' for '36:15:00', whereas %h wraps to a 12-hour clock.
Syntax
TIME_FORMAT(time, format)
time: ATIMEorDATETIMEexpression.format: A string containing time specifiers (%H,%h,%i,%s,%f,%p,%r,%T).
Practical Example
Suppose demo_employees records shift start times in shift_start. You can display both 24-hour and 12-hour readable labels for a scheduling screen.
SELECT
employee_id,
full_name,
TIME_FORMAT(shift_start, '%h:%i %p') AS twelve_hour_start,
TIME_FORMAT(shift_start, '%H:%i:%s') AS twenty_four_hour
FROM demo_employees
WHERE employee_id BETWEEN 1 AND 3;
| employee_id | full_name | twelve_hour_start | twenty_four_hour |
|---|---|---|---|
| 1 | Maya Patel | 08:30 AM | 08:30:00 |
| 2 | Liam Chen | 02:15 PM | 14:15:00 |
| 3 | Sofia Diaz | 11:45 PM | 23:45:00 |
Using %h:%i %p converts 14:15:00 cleanly into '02:15 PM' for user-facing schedules.
Common Mistakes & NULL Behavior
The most common mistake is passing date specifiers like %Y, %m, or %d to TIME_FORMAT(). Unlike DATE_FORMAT(), TIME_FORMAT() cannot read year, month, or day parts—those specifiers return NULL or 0 ('0000', '00'). Always use DATE_FORMAT() when formatting calendar dates alongside times.
Another frequent bug is writing %m instead of %i for minutes. %m stands for numeric month, so TIME_FORMAT('14:30:00', '%H:%m') prints '14:00' or NULL instead of '14:30'.
TIME_FORMAT() returns NULL if time or format is NULL, or if time is not a valid TIME/DATETIME expression.
Frequently Asked Questions
Can TIME_FORMAT() format durations longer than 24 hours?
Yes. Passing '48:10:00' with '%H hours %i mins' returns '48 hours 10 mins'.
Why did TIME_FORMAT(NOW(), '%Y-%m-%d %H:%i') fail?
TIME_FORMAT() ignores date parts and outputs '0000-00-00' or NULL for %Y, %m, and %d. Use DATE_FORMAT() for full date and time formatting.
Which specifier outputs minutes without leading zeros?
MySQL does not have a single-digit minute specifier; %i always outputs two-digit minutes (00 to 59).
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.