如何获取今天半夜到昨天半夜的数据

How to get data from today's midnight to Yesterday's midnight

我要查找从今天午夜到昨天午夜的数据。如今天的日期“2020-06-10 03:20:25”。我想在“2020-06-09 00:00:00”到“2020-06-10 00:00:00”

之间创建日期

假设 createdatetimestamp 列:

where createdate >= date_trunc('day', current_timestamp) - interval '1 day'
  and createdate < date_trunc('day', current_timestamp) + interval '1 day';
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

假设createdate是数据类型timestamp,可以简单的写成:

WHERE createdate >= CURRENT_DATE - 1
AND   createdate <  CURRENT_DATE

CURRENT_DATEreturns当前date。您可以添加/减去 integer 值以添加/减去天数。

timestamp 相比,date 被强制到当天的第一个瞬间。所以 date '2020-06-09' 等于 timestamp '2020-06-09 00:00:00'.

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