unix_millis:获取 Unix 毫秒时间戳
速查结论
unix_millis(timestamp) 是 Spark SQL 中用于将时间戳转换为 Unix 毫秒数的函数。返回自 1970-01-01 00:00:00 UTC 以来的毫秒数,精度截断到毫秒级。
语法
unix_millis(timestamp)
参数说明
| 参数 | 说明 |
|---|---|
timestamp | 时间戳表达式 |
返回值:自 1970-01-01 00:00:00 UTC 以来的毫秒数(BIGINT 类型)。更高精度的部分(微秒、纳秒)会被截断。
Since: 3.1.0
示例
基础用法
-- 1秒后的时间戳 = 1000毫秒
SELECT unix_millis(TIMESTAMP('1970-01-01 00:00:01Z'));
-- 结果: 1000
实际场景
-- 计算两个时间戳之间的毫秒差
SELECT
unix_millis(end_time) - unix_millis(start_time) AS duration_ms
FROM events;
-- 将当前时间转为毫秒时间戳
SELECT unix_millis(current_timestamp()) AS now_ms;
unix_millis vs unix_timestamp vs unix_seconds 对比
| 函数 | 返回单位 | 返回类型 | 精度 |
|---|---|---|---|
unix_millis(timestamp) | 毫秒 | BIGINT | 毫秒级(截断更细精度) |
unix_timestamp([timeExp[, fmt]]) | 秒 | BIGINT | 秒级 |
unix_seconds(timestamp) | 秒 | BIGINT | 秒级 |
SELECT
unix_millis(TIMESTAMP('1970-01-01 00:00:01Z')) AS millis, -- 1000
unix_timestamp('1970-01-01 00:00:01') AS seconds, -- 1
unix_seconds(TIMESTAMP('1970-01-01 00:00:01Z')) AS secs; -- 1
选型建议:
- 需要毫秒级时间差(如性能监控、延迟计算):用
unix_millis - 只需要秒级精度(如日期计算):用
unix_timestamp或unix_seconds
常见报错与避坑指南
精度截断
unix_millis 会截断更高精度(微秒、纳秒),不会四舍五入。
-- 微秒部分被截断,不是四舍五入
SELECT unix_millis(TIMESTAMP('1970-01-01 00:00:00.999999Z'));
-- 结果: 999(不是 1000)
参数为空
timestamp 参数为 NULL 时,结果也为 NULL。
SELECT unix_millis(NULL);
-- 结果: NULL
📱关注公众号
「数据仓库技术」文章同步更新,不错过每一篇干货

💬加群交流
备注「数据仓库技术」加入社群,每日一道大厂SQL真题
