Greenplum数据库,也就是我们常说的gp数据库,其SQL语法与hive、mysql等有些不同,现将常用的时间操作函数整理如下,以供参考。

  1. 获取当前时间、当前日期。

select now();                   -- 当前日期时间
>> 2023-02-28 07:45:43.24568+08
select current_time;            -- 当前时间
>> 07:45:43.24568+08
select current_date;            -- 当前日期
>> 2023-02-28
select date(now());             -- 当前日期
>> 2023-02-28
  1. 获取当前时间的后一年、后一个月、后一天等。

select now()::timestamp + '1 year';        -- 当前时间后一年,'-1 year'表示前一年
select now()::timestamp + '1 month';        -- 当前时间后一个月
select now()::timestamp + '1 day';        -- 当前时间后一天
select now()::timestamp + '1 hour';        -- 当前时间后一个小时
select now()::timestamp + '1 min';        -- 当前时间后一分钟
select now()::timestamp + '1 sec';        -- 当前时间后一秒钟
  1. 那年今日。

select current_date - interval '1 day';           -- 昨天日期
select current_date - interval '1 month';         -- 上月当日日期
select current_date - interval '1 year';          -- 去年当日日期
select date_trunc('months',now())::date;          -- 当月第一天
select now() + interval '3 day' + interval '4 hour';  -- 当前时间后三天四小时
  1. 时间格式转换。

select extract(epoch from cast('2023-02-28 07:45:43' as timestamp));    -- 时间转时间戳
select to_timestamp(1592280928);                                      -- 时间戳转时间
select now()::text;                                           -- 时间转字符串
select to_char(now(),'yyyy-mm-dd hh:mi:ss.us');                         -- 时间格式化(十二小时制)
select to_char(now(),'yyyy-mm-dd hh24:mi:ss.us');                       -- 时间格式化(二十四小时制)
  1. 去除时区。

select timestamp without time zone '2023-02-28 07:45:43.24568+08';        -- 去除时区

想学习更多的Excel、Python、SQL等数据分析知识,欢迎关注WX公众号:且听数据说。等着你来。

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐