如何从今天的午夜到昨天的午夜

时间:2020-06-10 16:17:32

标签: sql postgresql date-arithmetic

我正在寻找从今天的午夜到昨天的午夜的数据。如果今天是“ 2020-06-10 03:20:25”。我想在“ 2020-06-09 00:00:00”到“ 2020-06-10 00:00:00”之间创建

3 个答案:

答案 0 :(得分:1)

假设createdatetimestamp列:

where createdate >= date_trunc('day', current_timestamp) - interval '1 day'
  and createdate < date_trunc('day', current_timestamp) + interval '1 day';

答案 1 :(得分:1)

create table midnight_test(id int, createdate timestamptz);
insert into midnight_test values (1, '06/08/2020 17:15'), (2, '06/09/2020 00:00'), (3, '06/09/2020 13:25'), (4, '06/10/2020 00:00');
select * from midnight_test where createdate between '06/09/2020 00:00'::timestamptz and '06/10/2020 00:00'::timestamptz;

id |       createdate       
----+------------------------
  2 | 2020-06-09 00:00:00-07
  3 | 2020-06-09 13:25:00-07
  4 | 2020-06-10 00:00:00-07

答案 2 :(得分:1)

假设createdate是数据类型timestamp,它可以很简单:

WHERE createdate >= CURRENT_DATE - 1
AND   createdate <  CURRENT_DATE

CURRENT_DATE返回当前的date。您可以添加/减去integer值以添加/减去天数。

timestamp相比,date被强制到当天的第一时刻。因此date '2020-06-09'等于timestamp '2020-06-09 00:00:00'

顺便说一句,BETWEEN is almost always the wrong tool for timestamps.参见:

相关问题