// dates & times reference

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.

カテゴリ
Dates & times
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.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

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.