Postgresql 日期函数
2022-02-09 本文已影响0人
zhiwliu
取时间
- now()/current_timestamp: 这两个是等价的;
- timeofday(): 包括了日期,星期; 这个函数跟上面两个的不同是:
在一个事务里,now(),current_timestamp不管执行多少次都是同一个值;
但是timeofday()每次都是不完全一样的 - select current_date, current_time; 取当前日期和当前时间
时间截取(extract)
field可以是year,month,day,hour,minute,second,epoch(转成了timestamp,也就是自从1970-01-01距离的秒数);
也可以是dof(一年的第几天)
具体参数: https://www.postgresqltutorial.com/postgresql-extract/
select extract(year from now())
时间计算
通过interval加减, 下面的SQL是把interval关键字给省略了;
auditdb=# select now() + '1m';
?column?
-------------------------------
2022-02-09 08:17:46.622117+00
(1 row)
auditdb=# select now() + '1m -1d';
?column?
-------------------------------
2022-02-08 08:17:55.529641+00
(1 row)
auditdb=# select now() + '1m -1h';
?column?
-------------------------------
2022-02-09 07:18:09.819771+00
取两个时间差
取两个时间之间的秒数
auditdb=# select extract(epoch FROM ('2020-10-13'::timestamp - '2020-10-12'::timestamp));
date_part
-----------
86400
取两个日期之间的天数
auditdb=# select '2020-10-13'::date - '2020-10-14'::date;
?column?
----------
-1
(1 row)
auditdb=# select '2020-10-13'::date - '2020-10-14 08:24:24'::date;
?column?
----------
-1
取当前月的第一天
auditdb=# select date_trunc('month',generate_series(date'2021-1-10','2021-08-03', interval '1 month'));
date_trunc
------------------------
2021-01-01 00:00:00+00
2021-02-01 00:00:00+00
2021-03-01 00:00:00+00
2021-04-01 00:00:00+00
2021-05-01 00:00:00+00
2021-06-01 00:00:00+00
2021-07-01 00:00:00+00
取上个月的最后一天
select date_trunc('month',generate_series(date'2021-1-10','2021-08-03', interval '1 month'))-interval '1 day';
?column?
------------------------
2020-12-31 00:00:00+00
2021-01-31 00:00:00+00
2021-02-28 00:00:00+00
2021-03-31 00:00:00+00
2021-04-30 00:00:00+00
2021-05-31 00:00:00+00
2021-06-30 00:00:00+00