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

Posted

技术标签:

【中文标题】Scala - 如何在 Spark SQL 查询中将日期字符串转换为时间戳?【英文标题】:Scala - How to convert a Date String to a timestamp in a Spark SQL query? 【发布时间】:2019-10-30 13:44:11 【问题描述】:

我有一个 formattedDataInputDateTime 字符串,我想将它作为 Timestamp 类型作为第二个字段插入到表中。

// 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

【问题讨论】:

"$formattedDataInputDateTime" 不正确。你需要$"formattedDataInputDateTime"。 $ 和第一个 " 颠倒了。(我一直这样做)。它可能无法为您解决所有问题,但需要更改。 【参考方案1】:

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"

【讨论】:

我已将其更改为$"formattedDataInputDateTime",但并没有解决问题。 您能否使用可重现的代码 sn-p 更新您的问题,以便我们了解发生了什么?【参考方案2】:

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

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

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

【讨论】:

formattedDataInputDateTime 不是列名,它是我需要作为时间戳传递的字符串 2019-10-30T13:00:00.000+0000

以上是关于Scala - 如何在 Spark SQL 查询中将日期字符串转换为时间戳?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Spark Scala SQL 查询中包含 0 值?

将 spark.sql 查询转换为 spark/scala 查询

spark sql - 如何在 spark sql 中编写动态查询

Spark/scala 中的 SQL 查询

scala可以使用sparksql查询吗

如何在 Scala 中使用 Spark SQL 返回多个 JSON 对象