TO_TIMESTAMP 函数
to_timestamp(expr [, fmt])
功能描述
TO_TIMESTAMP 函数用于将不同类型的日期时间表达式(expr)转换为时间戳(timestamp)类型。如果提供了 fmt 参数,函数将根据指定的格式进行解析;若未提供 fmt,则按照默认的格式进行转换。如果 expr 中的日期时间格式不正确,函数将返回 null。
参数说明
- expr (string): 需要转换的字符串表达式。
- fmt (string, 可选): 指定字符串表达式中日期时间的格式。
返回结果
转换后的时间戳(timestamp)。
使用示例
-
将字符串转换为时间戳(不指定 fmt 参数):
SELECT to_timestamp('2022-02-01 10:23:32.121') as res;
+-------------------------+
| res |
+-------------------------+
| 2022-02-01 10:23:32.121 |
+-------------------------+
-
根据指定的格式将字符串转换为时间戳:
SELECT to_timestamp('2022/02/01 10:23:32.121', 'yyyy/MM/dd HH:mm:ss.SSS') as res;
+-------------------------+
| res |
+-------------------------+
| 2022-02-01 10:23:32.121 |
+-------------------------+
-
将不同类型的日期时间字符串转换为时间戳:
SELECT to_timestamp('01-02 10:23:32', 'dd-MM HH:mm:ss') as res;
+---------------------+
| res |
+---------------------+
| 1970-02-01 10:23:32 |
+---------------------+
-
转换非法日期时间字符串:
SELECT to_timestamp('2022-02-30 10:23:32.121') as res;
+-----+
| res |
+-----+
| |
+-----+
请注意,TO_TIMESTAMP 函数在处理非法日期时间字符串时会返回 null。因此,在使用该函数时,请确保输入的字符串格式正确。同时,可以通过 fmt 参数灵活地处理不同格式的日期时间字符串。