SQL TIME_TO_SEC function
Returns the time as seconds past midnight, or a duration back as a time: arithmetic-friendly seconds instead of HH:MM:SS strings.
- Catégorie
- Dates & times
- Returns
integer / time- In this category
- 56 of 121
Syntaxe
TIME_TO_SEC('09:30:00')
SEC_TO_TIME(34200)
AVG(TIME_TO_SEC(shift)) -- duration math
Each block is a separate form. The support table and the examples show which engine takes which.
Prise en charge des moteurs
| Moteur | Support | Notes |
|---|---|---|
| SQL Server | Different name or syntax | DATEDIFF(second, '00:00:00', t); DATEADD(second, n, CAST('00:00' AS time)) reverses |
| PostgreSQL | Different name or syntax | EXTRACT(epoch FROM t::interval) and make_interval(secs => n) |
| MySQL | Oui | Supported under this name. |
| SQLite | Different name or syntax | arithmetic on strftime('%s') |
| Oracle | Different name or syntax | numeric interval arithmetic |
Exemples
MySQL
SELECT TIME_TO_SEC('09:30:00') AS s; -- 34200
MySQL
SELECT SEC_TO_TIME(AVG(TIME_TO_SEC(shift_len))) AS avg_shift FROM shifts;
PostgreSQL
SELECT EXTRACT(epoch FROM interval '9 hours 30 minutes') AS s;
Bon à savoir
- Values past 24 hours keep counting: TIME_TO_SEC('25:00:00') is 90000, because MySQL's TIME is also a duration type.
- Negative durations come back negative: SEC_TO_TIME(-3600) is -01:00:00, which breaks parsers expecting clock times.
- Averaging clock times directly is wrong on every engine; convert to seconds, average, and convert back with SEC_TO_TIME.
Questions about TIME_TO_SEC / SEC_TO_TIME
How do I average a time column?
Not directly: MySQL's AVG on a TIME treats 09:30:00 as the number 93000. TIME_TO_SEC each row, average the integers, then SEC_TO_TIME the result.
What does TIME_TO_SEC of a duration return?
Seconds, sign included and past-24h counts kept: 25:00:00 gives 90000. Cast or modulo 86400 if you need clock-time semantics.
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.