Lesson

MySQL TIME_TO_SEC() Function

10 min reading
Free Course

MySQL TIME_TO_SEC() Function

The MySQL TIME_TO_SEC() function converts a TIME expression (or the time part of a DATETIME) into total seconds. It computes (hours * 3600) + (minutes * 60) + seconds and returns an integer (or decimal if fractional seconds exist).

Summing or averaging TIME columns directly in SQL yields misleading base-10 arithmetic results. Converting durations with TIME_TO_SEC() lets you calculate averages, percentages, or billing totals cleanly in seconds, then convert back with SEC_TO_TIME().

For example, '01:02:05' becomes 3725 seconds, and '25:00:00' becomes 90000 seconds.

Syntax

TIME_TO_SEC(time)
  • time: A valid TIME or DATETIME expression.

Practical Example

Suppose demo_employees logs daily shift durations in a TIME column named worked_duration. You can compute total and average worked seconds, then convert the average back to HH:MM:SS.

SELECT
    department_id,
    SUM(TIME_TO_SEC(worked_duration)) AS total_seconds,
    SEC_TO_TIME(ROUND(AVG(TIME_TO_SEC(worked_duration)))) AS avg_duration
FROM demo_employees
GROUP BY department_id
ORDER BY department_id;
department_id total_seconds avg_duration
10 144900 08:03:00
20 112500 07:48:45

Pairing TIME_TO_SEC() with SEC_TO_TIME() prevents base-60 overflow bugs when aggregating durations.

Common Mistakes & NULL Behavior

Watch out when passing a DATETIME value to TIME_TO_SEC(). It completely ignores the date portion and converts only the time-of-day since midnight (00:00:00). For instance, '2026-05-10 01:00:00' and '2020-01-01 01:00:00' both return 3600! Do not use TIME_TO_SEC() to compare two timestamps on different dates; use UNIX_TIMESTAMP() or TIMESTAMPDIFF() instead.

Negative TIME values return negative seconds: TIME_TO_SEC('-00:10:00') evaluates to -600.

TIME_TO_SEC() returns NULL if time is NULL or cannot be parsed as a valid TIME or DATETIME (such as '999:00:00', which exceeds MySQL's 838:59:59 limit).

Frequently Asked Questions

What is the inverse of TIME_TO_SEC()?

SEC_TO_TIME(seconds) converts integer or decimal seconds back into a MySQL TIME value.

Does TIME_TO_SEC() keep fractional seconds?

Yes. Passing '00:01:05.250' returns 65.250 (a decimal numeric value) rather than truncating the .250.

Can TIME_TO_SEC() replace UNIX_TIMESTAMP() for DATETIME math?

No. TIME_TO_SEC() drops the calendar date completely and only measures seconds since midnight.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum