pgsql 日期函数使用

1.date_part 函数日期相减得到相差天数.

select date_part('day', '2021-01-20 17:05'::timestamp - '2021-01-14 16:05'::timestamp);

2. date_part 获取当前日期周数

SELECT date_part('week',TIMESTAMP '2021-03-29');

3. date_trunc 获取当前周的周一日期

SELECT date_trunc('week', '2021-03-18'::timestamp);

4. 接下来 介绍 Postgresql 的trunc函数.

截断数字类型函数trunc为数字截断函数.移步postgresql: trunc函数.
截断日期类型函数date_trunc(text,time/timestamp/timestamptz);

select date_trunc('month',now()) +interval '12 h';
//每月1号 12点
select date_trunc('month',now()) + interval '15 d 9 h 30 min';
//每月15号9点半
select date_trunc('day',now()) + interval '9 h';
//每天9点
select date_trunc('day',now()) + interval '7 d';
//每周的今天
select date_trunc('weak',now()) + interval '1d 1minute';
//每周的周二第一分钟
select date_trunc('h',now()) + interval '30 minute';
//每小时
select date_trunc('minute',now()) + interval '30 second';
//每分钟
select date_trunc('minute',now()) + interval '30 minute 30 second';
//每30分钟
select date_trunc('quarter',now()) + interval '15 d 15 h 15 minute 30 second';
//本季度的第15天,15小时 15分 30秒
select date_trunc('quarter',now() ) - interval '1 h';
//每个季度最后一天的晚上11点
select date_trunc('quarter',now() + interval '3 month') - interval '1 h';

补充:

me=# select date_trunc('day',date '2018-05-15 09:00:00+08') + interval '9 h';
?column?
------------------------
2018-05-15 09:00:00+08
(1 行记录)
me=# select date_trunc('day',date '2018-05-15 14:09:04.127444+08') + interval '9 h';
?column?
------------------------
2018-05-15 09:00:00+08
(1 行记录)
me=# select date_trunc('day',date '2018-05-14 14:09:04.127444+08') + interval '9 h';
?column?
------------------------
2018-05-14 09:00:00+08
(1 行记录)
me=# select date_trunc('day',time '2018-05-14 14:09:04.127444+08') + interval '9 h';
?column?
----------
09:00:00
(1 行记录)
me=# select date_trunc('day',timestamp '2018-05-14 14:09:04.127444+08') + interval '9 h';
?column?
---------------------
2018-05-14 09:00:00
(1 行记录)
me=# select date_trunc('day',timestamptz '2018-05-14 14:09:04.127444+08') + interval '9 h';
?column?
------------------------
2018-05-14 09:00:00+08
(1 行记录)
me=# select date_trunc('day',timestamptz '2018-05-14 14:09:04.127444+08'+ interval '9 h');
date_trunc
------------------------
2018-05-14 00:00:00+08
(1 行记录)
posted @   Lafite-1820  阅读(1723)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示