irpas技术客

PostgreSQL中获取本周、本月和本年等等日期函数_~疆_pgsql获取当前月份

网络 7521

获取当前日期时间 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?

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

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


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #pgsql获取当前月份 #获取当前日期时间select #NOWSELECT #to_char #NOW