欢迎来到科站长!

PostgreSQL

当前位置: 主页 > 数据库 > PostgreSQL

postgresql 日期查询最全整理

时间:2024-09-22 15:17:43|栏目:PostgreSQL|点击:

1、获取当前日期

1
select now();

在这里插入图片描述

1
select current_timestamp;

在这里插入图片描述

返回值均是当前年月日、时分秒,且秒保留6位小数,两种方式等价

1
select current_time;

在这里插入图片描述

返回值:时分秒,秒最高精确到6位

1
select current_date;

在这里插入图片描述

返回值:年月日

2、查询今天的数据

1
select * FROM 表名 WHERE 时间字段 >= current_date AND 时间字段 < current_date + 1;

3、查询昨天的数据

1
select * FROM 表名 WHERE 时间字段 >= current_date - 1 AND 时间字段 < current_date;

4、查询一个月内的数据

1
select * FROM 表名 WHERE 时间字段 >= current_date - interval '1 month' AND 时间字段 <= current_date;

5、按日, 周, 月, 季度, 年统计数据

1
select date_trunc('DAY', 时间字段) as statisticTime, 分组字段, count(0) from 表名 GROUP BY date_trunc('DAY', 时间字段), 分组字段

日: DAY; 周: WEEK; 月: MONTH; 季度: QUARTER; 年: YEAR

6、 查询昨天、上周、上月、上年的日期

1
2
3
4
select to_char( now() - interval '1 day','yyyy-mm-dd');
select to_char( now() - interval '1 week','yyyy-mm-dd hh:mi:ss');
select to_char( now() - interval '1 month','yyyy-mm-dd');
select to_char( now() - interval '1 year','yyyy-mm-dd');

7、查询今天、今月、今年的开始的日期时间

1
2
3
4
5
6
select date_trunc('year', now())
select date_trunc('month', now())
select date_trunc('day', now())
select date_trunc('hour', now())
select date_trunc('minute', now())
select date_trunc('second', now())

8、查询最近1秒,1分,1小时,1天,1周(7天),1月,1年的记录

1
2
3
4
5
6
7
select * from 表名 where timestamp_start >= current_timestamp - interval ' 1 seconds '
select * from 表名 where timestamp_start >= current_timestamp - interval ' 1 minutes'
select * from 表名 where timestamp_start >= current_timestamp - interval ' 1 hours'
select * from 表名 where timestamp_start >= current_timestamp - interval ' 1 day'
select * from 表名 where timestamp_start >= current_timestamp - interval ' 7 day'
select * from 表名 where timestamp_start >= current_timestamp - interval ' 1 month'
select * from 表名 where timestamp_start >= current_timestamp - interval ' 1 year'

9、从时间戳中提取 年月日时分秒、周

1
2
3
4
5
6
7
select date_part('year', timestamp '2024-02-16 12:38:40')
select date_part('month', timestamp '2024-02-16 12:38:40')
select date_part('day', timestamp '2024-02-16 12:38:40')
select date_part('hour', timestamp '2024-02-16 12:38:40')
select date_part('minute', timestamp '2024-02-16 12:38:40')
select date_part('second', timestamp '2024-02-16 12:38:40')
select date_part('week', timestamp '2024-02-16 12:38:40')


上一篇:使用python-slim镜像遇到无法使用PostgreSQL的问题及解决方法

栏    目:PostgreSQL

下一篇:Postgres copy命令导入导出数据的操作方法

本文标题:postgresql 日期查询最全整理

本文地址:https://www.fushidao.cc/shujuku/802.html

广告投放 | 联系我们 | 版权申明

申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:257218569 | 邮箱:257218569@qq.com

Copyright © 2018-2025 科站长 版权所有冀ICP备14023439号