PostgreSQL中获取本周、本月和本年等等日期函数-年月日time

时间:2024-10-18 07:41:33

获取当前日期时间

select now();

select current_timestamp;

 

select to_char( now(),'yyyy-mm-dd hh:mi:ss');

  

注意:如果是表的话,从时间戳字段中提取小时(hh24):

select to_char(时间戳字段,'yyyy-mm-dd hh24:mi:ss');

hh默认是12,可指定:hh12,hh24。 

获取当前日期

select current_date;

select to_char( now(),'YYYY-MM-DD');

获取当前时间

select current_time;

 获取昨天、上周、上月、上年的日期

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');

获取前年的年份

select to_char( now() - interval '2 year','yyyy');

 

获取今天、今月、今年的开始的日期时间-基于date_trunc()

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())

 

获取今天、今月、今年的记录

select * from testdb where timestamp_start >= date_trunc( 'day', now() );
select * from testdb where timestamp_start >= date_trunc( 'month', now() );
select * from testdb where timestamp_start >= date_trunc( 'year', now() );

获取最近1秒,1分,1小时,1天,1周(7天),1月,1年的记录 

select * from testdb where timestamp_start >= current_timestamp - interval ' 1 seconds '
select * from testdb where timestamp_start >= current_timestamp - interval ' 1 minutes'
select * from testdb where timestamp_start >= current_timestamp - interval ' 1 hours'
select * from testdb where timestamp_start >= current_timestamp - interval ' 1 day'
select * from testdb where timestamp_start >= current_timestamp - interval ' 7 day'
select * from testdb where timestamp_start >= current_timestamp - interval ' 1 month'
select * from testdb where timestamp_start >= current_timestamp - interval ' 1 year'

从时间戳中提取 年月日时分秒、周-基于date_part()

select date_part('year', timestamp '2001-02-16 20:38:40')
select date_part('month', timestamp '2001-02-16 20:38:40')
select date_part('day', timestamp '2001-02-16 20:38:40')
select date_part('hour', timestamp '2001-02-16 20:38:40')
select date_part('minute', timestamp '2001-02-16 20:38:40')
select date_part('second', timestamp '2001-02-16 20:38:40')
select date_part('week', timestamp '2001-02-16 20:38:40')

 

 注意:假设当前(now)时间戳是2022-02-28,从时间戳中获取年份可有如下方式:

select date_part('year', current_timestamp)
select date_part('year', now())
select date_part('year', timestamp '2022-02-28')
select date_part('year','2022-02-28'::timestamp)
select date_part('year', 数据表中的时间戳字段名)

注意:可提取year、month、day、hour、minute、second 

注意:提取时间戳中的各个年月日时分秒有以下两种方式:

  1. select date_part('hour', 数据表中的时间戳字段名)    提取的小时如:1,2,3,,23,24
  2. select to_char(数据表中的时间戳字段名,'hh24');      提取的小时如:01,02,03,,23,24

获取两个时间相差的分钟数

SELECT CURRENT_TIMESTAMP,EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP- TIMESTAMP '2023-02-06 15:15:00')) /60 as interval_minutes;