首页 > 解决方案 > 编辑:spark scala 内置 udf:to_timestamp() 忽略时间戳值的毫秒部分

问题描述

示例代码:

val sparkSession = SparkUtil.getSparkSession("timestamp_format_test")

import sparkSession.implicits._

val format = "yyyy/MM/dd HH:mm:ss.SSS"
val time = "2018/12/21 08:07:36.927"

val df = sparkSession.sparkContext.parallelize(Seq(time)).toDF("in_timestamp")

val df2 = df.withColumn("out_timestamp", to_timestamp(df.col("in_timestamp"), format))

输出:

df2.show(假)

请注意:out_timestamp 会丢失原始值的毫秒部分

+-----------------------+-------------------+
|in_timestamp           |out_timestamp      |
+-----------------------+-------------------+
|2018/12/21 08:07:36.927|2018-12-21 08:07:36|
+-----------------------+-------------------+

df2.printSchema()

root
 |-- in_timestamp: string (nullable = true)
 |-- out_timestamp: timestamp (nullable = true)

在上面的结果中: in_timestamp 是字符串类型,我想转换为时间戳数据类型,它确实得到了转换,但毫秒部分丢失了。任何想法。?谢谢。!

标签: scalaapache-sparkapache-spark-sql

解决方案


在从字符串到时间戳的转换过程中保留毫秒的示例代码。

val df2 = df.withColumn("out_timestamp", to_timestamp(df.col("in_timestamp")))

df2.show(false)

+-----------------------+-----------------------+
|in_timestamp           |out_timestamp          |
+-----------------------+-----------------------+
|2018-12-21 08:07:36.927|2018-12-21 08:07:36.927|
+-----------------------+-----------------------+


scala> df2.printSchema
root
 |-- in_timestamp: string (nullable = true)
 |-- out_timestamp: timestamp (nullable = true)

您只需要从 to_timestamp 中删除格式参数。这将使用类似于字符串值的数据类型时间戳保存您的结果。


推荐阅读