In PostgreSQL, we can use the +
operator to add one or more hours to a time value.
By “time” value, this could be an actual time
value, a timestamp
, or an interval
. We can also add hours to a date
value or a date
and time
combination.
Example
We can specify intervals when adding to dates and times. For example, we can use hour
or hours
to add one or more hours:
SELECT time '08:35' + interval '1 hour';
Result:
09:35:00
Plural
And in plural form:
SELECT time '08:35' + interval '2 hours';
Result:
10:35:00
Timestamps
And here it is with a timestamp
value:
SELECT timestamp '2030-01-20 08:35' + interval '2 hours';
Result:
2030-01-20 10:35:00
Intervals
We can also add hours to an interval
:
SELECT interval '23 hours' + interval '2 hours';
Result:
25:00:00
Dates
We can even add hours to a date
value:
SELECT date '2030-01-20' + interval '3 hours';
Result:
2030-01-20 03:00:00
The result is a timestamp
value.
Date & Time Values Combined
We can also add a date
and time
value together, and add hours to that:
SELECT date '2030-01-20' + time '02:35' + interval '3 hours';
Result:
2030-01-20 05:35:00
Specified in Minutes
Another way to do it is to specify the equivalent number in minutes:
SELECT time '15:45' + interval '60 minutes';
Result:
16:45:00
When doing this, we don’t need to be exactly on the hour. For example, we could add more than one hour, but less than two:
SELECT time '15:45' + interval '90 minutes';
Result:
17:15:00
Negative Values
It’s possible to perform date arithmetic with negative values. If we use a negative value with the +
operator, then the specified number of hours will be subtracted from the input date/time. But if we use it with the -
operator, then it will be added to the input date/time.
Example:
SELECT time '03:00' - interval '-2 hours';
Result:
05:00:00