[英]Converting TZ timestamp string to a given format in UTC using spark and scala
我有一個名為 lastModified 的列,如下所示,表示 GMT 中的時間。 “2019-06-24T15:36:16.000Z”
我想在 spark 中使用 scala 將此字符串格式化為yyyy-MM-dd HH:mm:ss格式。 為了實現這一點,我創建了一個帶有新列"ConvertedTS"的數據框。 這給出了不正確的時間。
我運行它的機器在美國/紐約時區。
df.withColumn("ConvertedTS", date_format(to_utc_timestamp(to_timestamp(col("lastModified"), "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"), "America/New_York"), "yyyy-MM-dd HH:MM:SS").cast(StringType))
我基本上是在 yyyy-MM-dd HH:mm:ss 中尋找格式化以下語句的結果
df.withColumn("LastModifiedTS", col("lastModified"))
目前對我有用的方法之一是 udf,但由於不推薦使用 udf,我一直在尋找更多可以使用的直接表達式。
val convertToTimestamp = (logTimestamp: String) => {
println("logTimeStamp: " + logTimestamp)
var newDate = ""
try {
val sourceFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
sourceFormat.setTimeZone(TimeZone.getTimeZone("GMT"))
val convertedDate = sourceFormat.parse(logTimestamp)
val destFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
destFormat.setTimeZone(TimeZone.getTimeZone("GMT"))
newDate = destFormat.format(convertedDate)
println("newDate: " + newDate)
} catch {
case e: Exception => e.printStackTrace()
}
newDate
}
//register for sql
EdlSparkObjects.sparkSession.sqlContext.udf.register("convertToTimestamp", convertToTimestamp)
// register for scala
def convertToTimestampUDF = udf(convertToTimestamp)
df.withColumn("LastModifiedTS", convertToTimestampUDF(col("lastModified")))
感謝您的幫助和指導。
第一次withColumn
嘗試就快withColumn
。 它只包含不正確的日期格式字符串yyyy-MM-dd HH:MM:SS
。 此外, cast(StringType)
是不必要的,因為date_format
已經返回 StringType 列。 以下是具有更正日期格式的示例代碼:
import org.apache.spark.sql.functions._
import spark.implicits._
val df = Seq(
(1, "2019-06-24T15:36:16.000Z"),
(2, "2019-07-13T16:25:27.000Z")
).toDF("id", "lastModified")
df.withColumn("ConvertedTS", date_format(to_utc_timestamp(to_timestamp(
$"lastModified", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"), "America/New_York"), "yyyy-MM-dd HH:mm:ss")
).
show(false)
// +---+------------------------+-------------------+
// |id |lastModified |ConvertedTS |
// +---+------------------------+-------------------+
// |1 |2019-06-24T15:36:16.000Z|2019-06-24 19:36:16|
// |2 |2019-07-13T16:25:27.000Z|2019-07-13 20:25:27|
// +---+------------------------+-------------------+
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.