在配置单元中将long转换为时间戳

gblwokeq  于 2021-05-29  发布在  Hadoop
关注(0)|答案(1)|浏览(622)

我想把spark应用程序的开始时间存储到表中。因此尝试了以下代码:

scala> val i = sc.startTime
i: Long = 1519308048128

这个查询会给出适当的时间戳 YYYY-MM-DD HH:M:SS.sss . 但如果我在insert语句中使用 spark.sql , NULL 值被插入到目标表中。

spark.sql("
  insert into table TST_DT
  select from_unixtime(CAST(${i}/1000 AS bigint),'YYYY-MM-DD HH:MM:SS.SSS') 
  from temp limit 1")

可瞄准的 TST_DT 只有数据类型为的列 Timestamp 我试过用 cast 在Hive中运行,结果仍然相同:-

spark.sql("
  insert into table TST_DT
  select cast(from_unixtime(CAST(${i}/1000 AS bigint),'YYYY-MM-DD HH:MM:SS.SSS') 
  as timestamp) from temp limit 1")
vdzxcuhz

vdzxcuhz1#

日期格式字符串不正确。请参阅simpledataformat

val df = sc.parallelize(Seq(sc.startTime/1000)).toDF("ts")

df.withColumn("ts" , from_unixtime($"ts" , "yyyy-MM-dd HH:mm:ss.SSS") ).show(false)
+-----------------------+
|ts                     |
+-----------------------+
|2018-02-22 05:35:19.000|
+-----------------------+

df.withColumn("ts" , from_unixtime($"ts" , "YYYY-MM-DD HH:MM:SS.SSS") ).show(false)
+-----------------------+
|ts                     |
+-----------------------+
|2018-02-53 05:02:00.000|
+-----------------------+

直到现在一切都很好因为 from_unixtime 返回字符串。但一旦你把它扔给 timestamp :

df.withColumn("ts" , from_unixtime($"ts" , "yyyy-MM-dd HH:mm:ss.SSS") )
  .selectExpr("cast(ts as timestamp)").show
+-------------------+
|                 ts|
+-------------------+
|2018-02-22 05:35:19|
+-------------------+

df.withColumn("ts" , from_unixtime($"ts" , "YYYY-MM-DD HH:MM:SS.SSS") )
  .selectExpr("cast(ts as timestamp)").show
+----+
|  ts|
+----+
|null|
+----+

相关问题