如何在PostgreSQL日期时间中增加天数


77

我有一张桌子projects

id title        created_at                     claim_window
1  Project One  2012-05-08 13:50:09.924437     5
2  Project Two  2012-06-01 13:50:09.924437     10

A)我想通过计算找到截止日期deadline = created_at + claim_window(No. of days)

像下面这样。

id title        created_at                     claim_window deadline
1  Project One  2012-05-08 13:50:09.924437     5            2012-05-13 13:50:09.924437
2  Project Two  2012-06-01 13:50:09.924437     10           2012-06-11 13:50:09.924437

B]我也想找到截止日期已经过去的项目

id title        created_at                     claim_window deadline
1  Project One  2012-05-08 13:50:09.924437     5            2012-05-13 13:50:09.924437

我尝试以下方法。

SELECT * FROM "projects" WHERE (DATE_PART('day', now()- created_at) >= (claim_window+1))

但是由于某种原因,它无法正常工作。

Answers:


130

这将给您截止日期:

select id,  
       title,
       created_at + interval '1' day * claim_window as deadline
from projects

要获得截止日期结束的所有项目,请使用:

select *
from (
  select id, 
         created_at + interval '1' day * claim_window as deadline
  from projects
) t
where localtimestamp at time zone 'UTC' > deadline

但是又发生了一个问题,我created_at的数据类型为timestamp without time zonecurrent_timestamp的数据类型timestamp with time zone,因此我没有得到正确的答案
Salil 2012年

@Salil:LOCALTIMESTAMPtimestamp without time zone
a_horse_with_no_name 2012年

@Salil:没关系,只要数据指向的是同一时间点,结果与timestamptimestamptz相同。添加一天对两者都有相同的效果。
Erwin Brandstetter,2012年

我的create_at被保存为UTC时间(不带时区),并且LOCALTIMESTAMP和CURRENT_TIMESTAMP给我的时间为+5.30,因此问题仍然没有得到解决
Salil

@Salil:然后使用localtimestamp at time zone 'UTC'
a_horse_with_no_name 2012年

17

对我来说,我必须将整个间隔用单引号引起来,而不仅仅是间隔的值。

select id,  
   title,
   created_at + interval '1 day' * claim_window as deadline from projects   

代替

select id,  
   title,
   created_at + interval '1' day * claim_window as deadline from projects   

Postgres日期/时间函数

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.