Scala-如何在Spark SQL查询中将日期字符串转换为时间戳?

问题描述 投票:0回答:2

我有一个formattedDataInputDateTime字符串,我想作为第二个字段的时间戳类型插入到表中。

// Returns 2019-10-30T13:00Z
val localDateTimeZoned = OffsetDateTime.of(java.time.LocalDate.parse(currentDate), java.time.LocalTime.now, ZoneOffset.UTC).truncatedTo(ChronoUnit.HOURS)

// Returns 2019-10-30T13:00:00.000+0000
val formattedDataInputDateTime: String = localDateTimeZoned.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSxx")).toString

所以我写了以下查询,但无法弄清楚如何在此处插入formattedDataInputDateTime作为时间戳?

spark.sql(
  s"""INSERT INTO main.basic_metrics
     |VALUES ('metric_name', ???,
     |'metric_type', current_timestamp, false)""".stripMargin)

我已经尝试测试这种方法,但是导致了以下错误:

val ts = cast(unix_timestamp("$formattedDataInputDateTime", "yyyy-MM-dd'T'HH:mm:ss.SSSxx") as timestamp)

type mismatch;
 found   : String("$formattedDataInputDateTime")
 required: org.apache.spark.sql.Column
java scala apache-spark datetime apache-spark-sql
2个回答
0
投票

val ts = cast(unix_timestamp("$formattedDataInputDateTime", "yyyy-MM-dd'T'HH:mm:ss.SSSxx") as timestamp)

type mismatch;
 found   : String("$formattedDataInputDateTime")
 required: org.apache.spark.sql.Column

这基本上意味着$位于引号中。它应该在$"formattedDataInputDateTime"

之外

0
投票

您传递的是String而不是Column,可以使用lit进行包装:

cast(unix_timestamp(lit(formattedDataInputDateTime), "yyyy-MM-dd'T'HH:mm:ss.SSSxx")

但是您可以获得当前日期并使用火花函数current_datedate_format对其进行格式化。

© www.soinside.com 2019 - 2024. All rights reserved.