flink1.12.x SQL:时间戳转换:TO_TIMESTAMP、FROM_UNIXTIME

说明

通过下面代码,说明这两个函数的作用:

package day6;


import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;


public class Std2agg {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);//自动模式,根据数据源自行判断
        //构建Table环境
        EnvironmentSettings bsSettings = EnvironmentSettings.newInstance().useBlinkPlanner().inStreamingMode().build();
        StreamTableEnvironment stEnv = StreamTableEnvironment.create(env, bsSettings);

        String sql="select from_unixtime(5) as from_unixtime,to_timestamp(from_unixtime(5)) as to_timestamp";
        Table res=stEnv.sqlQuery(sql);
        System.out.println("表结构:");
        res.printSchema();
        DataStream<Row> dsRes = stEnv.toAppendStream(res, Row.class);
        dsRes.map(new MapFunction<Row, Object>() {
            @Override
            public Object map(Row value) throws Exception {
                System.out.println("from_unixtime::::"+value.getField(0));
                System.out.println("to_timestamp::::"+value.getField(1));
                return value;
            }
        });
        env.execute();
    }
}

执行结果如下:

表结构:
root
 |-- from_unixtime: VARCHAR(2000)
 |-- to_timestamp: TIMESTAMP(3)

from_unixtime::::1970-01-01 08:00:05
to_timestamp::::1970-01-01T08:00:05

from_unixtime()

传入参数:是时间戳,即:距离 1970-01-01 00:00:00 的 秒 数

返回值:是 VARCHAR(2000) 类型,也就是字符串。
返回值格式为:yyyy-MM-dd HH:mm:ss,如:1970-01-01 08:00:50

to_timestamp()

传入参数:字符串类型的日期,格式:yyyy-MM-dd HH:mm:ss,如:to_timestamp('2022-12-11 14:25:00')

返回值:是 TIMESTAMP(3) 类型,精确到毫秒,所以值为:1970-01-01T08:00:50,中间有 T

字符类型转时间戳

可以格式化日期,如下:

SELECT TO_TIMESTAMP('2017-12-13 11:27:57', 'yyyy-MM-dd HH:mm:ss')

13位 bigint类型转时间戳

TO_TIMESTAMP 不能将 13位 bigint类型的UNIX时间戳(单位是纳秒) 转换成 TIMESTAMP ,否则报错:

Flink SQL> select TO_TIMESTAMP(1513135677000);
解决
SELECT TO_TIMESTAMP(FROM_UNIXTIME(1513135677000 / 1000, 'yyyy-MM-dd HH:mm:ss'))

原文出处:/show_1IX4Eu1PihRs.html