Calculating Intervals Between Times
Problem
You want to know the amount of time elapsed between two times.
Solution
Convert the times to seconds with TIME_TO_SEC( ) and take the difference.
For a difference represented as a time, convert the result back the
other way using SEC_TO_TIME( ).
Discussion
Calculating intervals between times is similar to adding times
together, except that you compute a difference rather than a sum. For
example, to calculate intervals in seconds between pairs of
t1 and t2 values, convert the
values in the time_val table to seconds using
TIME_TO_SEC( ), then take the difference. To
express the resulting difference as a TIME value,
pass it to SEC_TO_TIME( ). The following query
shows intervals both ways:
mysql>SELECT t1, t2,->TIME_TO_SEC(t2) - TIME_TO_SEC(t1) AS 'interval in seconds',->SEC_TO_TIME(TIME_TO_SEC(t2) - TIME_TO_SEC(t1)) AS 'interval as TIME'->FROM time_val;+----------+----------+---------------------+------------------+ | t1 | t2 | interval in seconds | interval as TIME | +----------+----------+---------------------+------------------+ | 15:00:00 | 15:00:00 | 0 | 00:00:00 | | 05:01:30 | 02:30:20 | -9070 | -02:31:10 | | 12:30:20 | 17:30:45 | 18025 | 05:00:25 | +----------+----------+---------------------+------------------+
Note that intervals may be negative, as is the case when
t1 occurs later than t2.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access