61

I have a table of items with the following columns:

  • start_time column (timestamp without time zone)
  • expiration_time_seconds column (integer)

For example, some values are:

SELECT start_time, expiration_time_seconds 
   FROM whatever 
       ORDER BY start_time;

         start_time         | expiration_time_seconds
----------------------------+-------------------------
 2014-08-05 08:23:32.428452 |                  172800
 2014-08-10 09:49:51.082456 |                    3600
 2014-08-13 13:03:56.980073 |                    3600
 2014-08-21 06:31:38.596451 |                    3600
 ...

How do I add the expiration time, given in seconds, to the start_time?

I have tried to format a time interval string for the interval command, but failed:

blah=> SELECT interval concat(to_char(3600, '9999'), ' seconds');
ERROR:  syntax error at or near "("
LINE 1: SELECT interval concat(to_char(3600, '9999'), ' seconds');

2 Answers 2

113

The trick is to create a fixed interval and multiply it with the number of seconds in the column:

SELECT start_time, 
       expiration_time_seconds, 
       start_time + expiration_time_seconds * interval '1 second'
FROM whatever 
ORDER BY start_time;

        start_time          | expiration_time_seconds |          end_time
----------------------------|-------------------------|----------------------------
 2014-08-05 08:23:32.428452 |                  172800 | 2014-08-07 08:23:32.428452
 2014-08-10 09:49:51.082456 |                    3600 | 2014-08-10 10:49:51.082456
 2014-08-13 13:03:56.980073 |                    3600 | 2014-08-13 14:03:56.980073
 2014-08-21 06:31:38.596451 |                    3600 | 2014-08-21 07:31:38.596451
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much! Can you add space to start_time + expiration_time_seconds to make it easy to visualize?
@bonafernando not sure I understand
I tried to edit his answer, but the amount of changes were so little I couldn't submit, then I added the comment above.
3

As of version 9.5 it is possible to create interval with make_interval function like this:

make_interval(secs => 10)

also intervals can be added to timestamps easily with + operand:

start_time + make_interval(secs => 10)

it will add 10 seconds to start_time and return a new timestamp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.