Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 701
Daniel Magliola Avatar asked Mar 01 '13 14:03

Daniel Magliola


People also ask

How do I declare a date variable in PostgreSQL?

To select the rows from the last x month, there is no need to store the current date and time in a variable to begin with. It's also easier to use make_interval() to generate an interval based on a specified unit. select * from live_table where updated_at <= current_date - make_interval(mons => p_pum_months);

How do I calculate hours between two dates in PostgreSQL?

Discussion: To calculate the difference between the timestamps in PostgreSQL, simply subtract the start timestamp from the end timestamp. Here, it would be arrival - departure . The difference will be of the type interval , which means you'll see it in days, hours, minutes, and seconds.


2 Answers

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.

like image 136
Erwin Brandstetter Avatar answered Sep 21 '22 15:09

Erwin Brandstetter


Found the answer, in another SO question:

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

Hope that helps anyone

like image 41
Daniel Magliola Avatar answered Sep 19 '22 15:09

Daniel Magliola