In SQLite, we can use the TIME()
function to add a given number of hours to a time value.
If we’re dealing with datetime values, we can use the DATETIME()
function.
Example
Here’s an example that uses the TIME()
function:
SELECT TIME('22:50:10', '+1 hour');
Result:
23:50:10
We can subtract the amount by replacing +
with -
.
Omitting +
results in the amount being added, as if we’d used +
:
SELECT TIME('22:50:10', '1 hour');
Result:
23:50:10
We can specify the hours in plural or non-plural form. That is, hour
is equivalent to hours
:
SELECT
TIME('22:50:10', '1 hour') AS hour,
TIME('22:50:10', '1 hours') AS hours;
Result:
hour hours -------- -------- 23:50:10 23:50:10
The DATETIME()
Function
This example uses the DATETIME()
function to add five hours to a datetime value:
SELECT DATETIME('2050-08-21', '+5 hours');
Result:
2050-08-21 05:00:00
In this case, I passed a date value and the function returned a datetime value with the number of hours being added to 00:00:00.
Here’s an example with a datetime value:
SELECT DATETIME('2050-08-21 22:30:45', '+5 hours');
Result:
2050-08-22 03:30:45
In this case the number of hours was enough to change the date.