[英]Scala - How to convert a Date String to a timestamp in a Spark SQL query?
[英]Convert the date string with timezone column to timestamp in spark scala
我需要将字符串(带时区的日期)列转换为时间戳。 转换后的时间戳列应具有与字符串字段相同的值。
有一个字符串字段,它具有日期和时间偏移量,我尝试将其转换为时间戳数据类型,它实际上转换为 UTC 格式,但我希望将偏移量作为时间戳数据类型具有相同的日期和时间。
Seq("2019-02-05T18:59:11.0874121+05:30").toDF("date_str")
.select($"date_str")
.withColumn("date_timestamp",$"date_str".cast("timestamp"))
.show(false)
我希望 date_timestamp 列应该有"2019-02-05T18:59:11.0874121+05:30"
但它实际上转换为UTC格式"2019-02-05T13:29:11.087+0000"
。
我使用 udf 将字符串转换为时间戳而不做任何更改。
import java.text.SimpleDateFormat
import java.sql.Timestamp
val convertToTimestamp= (logTimestamp: String) => {
try {
// change the date format as needed
val sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss','SSS")
val theDate = sdf.parse(logTimestamp)
new Timestamp(theDate.getTime)
} catch {
case _: Exception => null
}
}
//register for sql
sqlContext.udf.register("convertToTimestamp", convertToTimestamp)
//register for scala
def convertToTimestampUDF = udf(convertToTimestamp)
val newDfWithTimeStamp = oldDfWithString.select(convertToTimestampUDF($"date_timestamp ").alias("date_timestamp "))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.