文章目录
常用函数与常量
| 函数 | 说明 |
|---|---|
| current_time | 现在的时间 |
| current_date | 今天的日期 |
| current_timestamp | 当前日期和时间 |
| now() | 当前的日期和时间和current_timestamp一样 |
| localtime | time,当前时间 |
| localtimestamp | 当前日期和时间 |
| timeofday() | 字符串,当前日期和时间 |
| age(timestamp1, timestamp2) | 计算年纪,timestamp1-timestamp2,结果类型是interval,类似于:29 years 9 mons 27 days |
select current_date,current_time,current_timestamp,now(),localtime,localtimestamp,timeofday();

select age('2030-04-10', '2000-06-13');
第1个参数减第2个参数,age返回值是interval,很方便算年龄

-- 时间戳转字符串再截取
SELECT now()::timestamp,substring(''||now()::timestamp from 1 for 19);

to_timestamp(字符串转时间戳、数字转时间戳)
| 函数 | 说明 |
|---|---|
| to_timestamp(text, text) | 把字串转换成时间戳 |
| to_timestamp(double) | 把数字转时间戳 |
select to_timestamp(1859351600),to_timestamp('1859351600'::bigint),to_timestamp('2090 01 12', 'YYYY MM DD');

想要了解YYYY MM DD代表什么,可以参考后文:日期时间格式化字符串
date与to_date(字符串转日期、时间戳转日期)
| 函数 | 说明 |
|---|---|
| to_date(text, text) | 字串转日期,第1个参数是时间,第2个参数是格式化字符串 |
| date(timestamp) | 时间戳转日期 |
| date(text) | 字符串转日期 |
select to_date('2090 01 12', 'YYYY MM DD'),date(now()),date('2090-09-28');

在一些喜欢用字符串存时间的计算时非常有用,虽然不推荐在数据库上做计算,但是有时候有些特殊的项目,需要存储过程,这些函数能极大的简化计算。
例如,有些每日都要和前一日比(这里简化了只计算了日期):
select priceday,to_char(to_date(priceday, 'YYYYMMDD')-interval '1 day','YYYYmmdd') as lastDay from elt_data_table;
interval(时间计算)
interval还是非常有用,不仅仅可以用来表示时间差,还可以用来做时间计算。
基本操作与格式
| 操作符 | 说明 |
|---|---|
| year | 年 |
| month | 月 |
| day | 天 |
| hour | 小时 |
| min | 分钟 |
| sec | 秒 |
加不加s不影响,interval '2 day’和interval '2 days’都可以。
select now(),now() - interval '1 day' as subday,
now<

最低0.47元/天 解锁文章
1630

被折叠的 条评论
为什么被折叠?



