Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

time - Adding <integer> seconds to a <timestamp> in PostgreSQL

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');
question from:https://stackoverflow.com/questions/28528028/adding-integer-seconds-to-a-timestamp-in-postgresql

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...