SQL TIME_FORMAT function
Formats the time portion of a value: MySQL's TIME_FORMAT works on TIMEs, DATE_FORMAT covers datetimes, and TO_CHAR masks do it everywhere else.
- Returns
text- In this category
- 99 of 121
语法
TIME_FORMAT(time, '%H:%i:%s')
引擎支持
| 引擎 | Support | 备注 |
|---|---|---|
| SQL Server | Different name or syntax | FORMAT(d, 'HH:mm:ss') or CONVERT(varchar, d, 108) |
| PostgreSQL | Different name or syntax | to_char(d, 'HH24:MI:SS') |
| MySQL | 是 | TIME_FORMAT(t, '%H:%i:%s') / DATE_FORMAT |
| SQLite | Different name or syntax | strftime('%H:%M:%S', d) |
| Oracle | Different name or syntax | TO_CHAR(d, 'HH24:MI:SS') |
示例
MySQL
SELECT TIME_FORMAT('14:30:00', '%h:%i %p'); -- 02:30 PM
PostgreSQL
SELECT to_char(TIMESTAMP '2026-08-01 14:30:00', 'HH12:MI:SS AM'); -- 02:30:00 PM
SQLite
SELECT strftime('%H:%M', created_at) FROM events;
值得了解
- MySQL's TIME_FORMAT accepts only hour/minute/second-style codes: %Y or %d on a TIME return NULL or garbage; use DATE_FORMAT for datetimes.
- PostgreSQL's to_char on an interval reads the hour field: to_char(INTERVAL '30 hours', 'HH24') is 30, but to_char(INTERVAL '1 day 6 hours', 'HH24') is 06 because the day sits in its own field. EXTRACT(EPOCH FROM iv) / 3600 gives total hours.
- MySQL TIME values can be negative or above 24 hours (up to 838:59:59) and print as stored. PostgreSQL and SQL Server time types stop at one day, and Oracle has no TIME type.
Questions about TIME_FORMAT
Why does %H give 14 but %h gives 02?
%H is 00-23 (24-hour), %h (and MySQL's %I) is 01-12 and needs %p for the AM/PM marker. Mixing them gives wrong-but-plausible output.
How do I format an interval over 24 hours?
Not with time masks. In PostgreSQL: EXTRACT(EPOCH FROM iv)/3600 for total hours; in MySQL: TIMESTAMPDIFF(SECOND, ...) plus SEC_TO_TIME for display.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.