How to add a variable number of hours to a date in PostgreSQL?

SqlPostgresqlDatetime

Sql Problem Overview


Apparently, PostgreSQL doesn't have DATEADD, because you can just use the + or - operators.

I need to add a number of hours to a date, which is accomplished like this:

date_field + interval '8.25 hour' 

Which is great, but I need the number of hours to come from a field in the table. Would be something like this:

date_field + interval start_time 'hour' 

I can't find anywhere how to do this. Is this actually impossible?

I don't mind resorting to ugly hacks like taking the field value and dividing by 3600, multiplying by 86400. Whatever I need to do, but I haven't found any way to do that either.

Sql Solutions


Solution 1 - Sql

Since you want to add hours, it should rather be:

SELECT date_field + interval '1 hour' * start_time

start_time can be any numerical value.
'1 hour' can be shortened to '1h'.
interval can be multiplied by a scalar.

Solution 2 - Sql

Found the answer, in another SO question:

date + interval '1' minute * FLOOR(start_time * 60)

Hope that helps anyone

Solution 3 - Sql

The one worked for me is

SELECT date_field + interval '1' HOUR * start_time

start_time can be any numerical value.

Solution 4 - Sql

If anyone wants to add in time stamp then

select time '05:00' - interval '2 hours'	

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel MagliolaView Question on Stackoverflow
Solution 1 - SqlErwin BrandstetterView Answer on Stackoverflow
Solution 2 - SqlDaniel MagliolaView Answer on Stackoverflow
Solution 3 - SqlWillie ZView Answer on Stackoverflow
Solution 4 - SqlRohil PatelView Answer on Stackoverflow