MySQL SUBTIME() Function
The SUBTIME()
function in MySQL subtracts a time interval from a datetime or time value. This is useful for calculating past times or for adjusting timestamps.
SUBTIME(): Definition and Usage
SUBTIME()
takes a datetime or time value and a time interval as input. It returns a new datetime or time value after subtracting the interval. You can add time by using a negative value for the time interval. The input time should be in 'HH:MM:SS' or 'HH:MM:SS.mmmmmm' format.
Syntax
Syntax
SUBTIME(datetime, time_interval)
Parameter Values
Parameter | Description |
---|---|
datetime |
The original datetime or time value. This is required. |
time_interval |
The time interval to subtract (positive) or add (negative). This is required. The format is HH:MM:SS or HH:MM:SS.mmmmmm. |
Examples
Subtracting Seconds
Subtracting 5.000001 seconds from a datetime value.
Syntax
SELECT SUBTIME("2017-06-15 10:24:21.000004", "5.000001");
Output
2017-06-15 10:24:15.000003
Subtracting Hours, Minutes, and Seconds
Subtracting a more complex time interval.
Syntax
SELECT SUBTIME("2017-06-15 10:24:21.000004", "3:2:5.000001");
Output
2017-06-15 07:22:16.000003
Subtracting Seconds from a TIME Value
Subtracting seconds from a time value (only the time part).
Syntax
SELECT SUBTIME("10:24:21", "5");
Output
10:24:16
Subtracting Minutes (as seconds) from a TIME Value
Subtracting 3 minutes (180 seconds) from a time value.
Syntax
SELECT SUBTIME("10:24:21", "180");
Output
10:21:01
Adding a Time Interval
Adding 3 hours, 2 minutes, and 5 seconds to a time value (using a negative interval).
Syntax
SELECT SUBTIME("10:24:21", "-3:2:5");
Output
13:26:26