一、获取系统时间和时间格式化
1、获取当前时间select now();select current_timestamp;select CURRENT_TIME;select LOCALTIME;select LOCALTIMESTAMP;select now()::timestamp without time zone –获取当前时间 ,不带时区select current_date; –获取当天日期 格式YYYY-MM-DD2、时间格式化select timestamp '2020-04-12 18:54:54'; –时间格式由字符串转换为timestamp,格式YYYY-DD-MM HH24:MI:SSselect date '2020-04-12 18:54:54'; –时间格式由字符串转换为date ,格式YYYY-MM-DDtimestamp '2020-04-12 18:54:54'是在函数中强制将字符串转换成timestamp的方法,在一般函数中此方法通用,后面不解释
二、时间截取
1、extract函数显示年select extract(year from now());select extract(year from timestamp '2020-04-12 18:54:54');显示月select extract(mon from now());显示日select extract(day from now());显示小时select extract(hour from now());显示分钟select extract(minutes from now());显示秒select extract(second from now());2、date_part函数显示年select date_part('year' ,timestamp '2020-04-12 18:54:54');显示月select date_part('month' ,timestamp '2020-04-12 18:54:54');
三、时间相加减换算
1、age函数执行:select age(timestamp '20200426',timestamp '20191008');结果:6 mons 18 days从上面例子可以看出age函数可以计算两个时间之间相差的具体年月日。age函数如果不输入第一个参数,那么默认会用当前时间代替,看下例:执行:select age(timestamp '20181008');结果:1 year 6 mons 18 days –当前系统时间减去时间20181008的结果2、如果现在想要查看两个时间之间有多少个月份,计算如下:执行:select (EXTRACT(YEAR from age(timestamp ‘20160114’,timestamp ‘19911008’))*12+EXTRACT(MONTH from age(timestamp ‘20160114’,timestamp ‘19911008’))+1)结果:292注意:上面的算法后面+1,逻辑是如果两个时间相差的天数不满一个月,那么也算一个月
四、日期计算
--使用interval当前时间加2天select now()+interval '2 day';当前时间减2天select now()-interval '2 day';当前时间减2个月select now()-interval '2 mon';当前时间减2小时select now()+interval '-2 hour';
