【问题标题】:Scala - How to convert a Date String to a timestamp in a Spark SQL query?Scala - 如何在 Spark SQL 查询中将日期字符串转换为时间戳?
【发布时间】: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"。 $ 和第一个 " 颠倒了。(我一直这样做)。它可能无法为您解决所有问题,但需要更改。

标签: java scala apache-spark datetime apache-spark-sql


【解决方案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
猜你喜欢
  • 2014-08-21
  • 2021-12-21
  • 1970-01-01
  • 2018-01-15
  • 2019-03-31
  • 2023-03-17
  • 1970-01-01
  • 2020-09-23
  • 1970-01-01
相关资源
最近更新 更多