scala - 编辑: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 是字符串类型,我想转换为时间戳数据类型,它确实得到了转换,但毫秒部分丢失了。任何想法。?谢谢。!
解决方案
在从字符串到时间戳的转换过程中保留毫秒的示例代码。
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 中删除格式参数。这将使用类似于字符串值的数据类型时间戳保存您的结果。
推荐阅读
- amazon-web-services - AWS_DEFAULT_REGION 和 AWS_REGION 系统变量有什么区别?
- textbox - RDLC报告:如何隐藏文本,取决于数据集中的所有字段是否为NULL?
- c# - 在不使用令牌/oauth 请求的情况下从控制器创建 OWIN OUath 令牌
- javascript - 如何使用 reduce 或数组方法将 Javascript 对象合并到数组中
- c# - 枚举到类型映射
- java - 我找不到为什么这个错误发生 java.lang.IncompatibleClassChangeError: null in spring boot applicaiton
- android - 以编程方式将文件保存到存储器
- java - 解析 json 后模块列表未出现
- selenium - 获取“元素应该是”选择“但在从下拉列表中获取数据时出现“选项”错误
- java - 如何在 log4j 2.12.1 中使用 loggingEvent 类