在 Spark Scala 中处理微秒 [英] Handling microseconds in Spark Scala
问题描述
我使用 Scala 将 PostgreSQL 表作为数据框导入到 spark 中.数据框看起来像
I imported a PostgreSQL table into spark as a dataframe using Scala. The dataframe looks like
user_id | log_dt
--------| -------
96 | 2004-10-19 10:23:54.0
1020 | 2017-01-12 12:12:14.931652
我正在将此数据帧转换为 log_dt 的数据格式为 yyyy-MM-dd hh:mm:ss.SSSSSS
.为此,我使用以下代码使用 unix_timestamp
函数将 log_dt 转换为时间戳格式.
I am transforming this dataframe to have the data format for log_dt as yyyy-MM-dd hh:mm:ss.SSSSSS
. To achieve this I used the following code to convert the log_dt to timestamp format using unix_timestamp
function.
val tablereader1 = tablereader1Df.withColumn("log_dt",unix_timestamp(tablereader1Df("log_dt"),"yyyy-MM-dd hh:mm:ss.SSSSSS").cast("timestamp"))
当我使用命令 tablereader1.show()
打印 tablereader1 数据帧时,我得到以下结果
When I print to print the tablereader1 dataframe using the command tablereader1.show()
I get the following result
user_id | log_dt
--------| -------
96 | 2004-10-19 10:23:54.0
1020 | 2017-01-12 12:12:14.0
如何将微秒保留为时间戳的一部分?任何建议表示赞赏.
How can I retain the microseconds as part of the timestamp? Any suggestions are appreciated.
推荐答案
Milleseconds with date_format()
你可以使用 Spark SQL date_format()
接受 Java SimpleDateFormat 模式.SimpleDateFormat
只能解析到毫秒模式为S".
Milleseconds with date_format()
You can use Spark SQL date_format()
which accepts Java SimpleDateFormat patterns. SimpleDateFormat
can parse till milleseconds only with pattern "S".
import org.apache.spark.sql.functions._
import spark.implicits._ //to use $-notation on columns
val df = tablereader1Df.withColumn("log_dt", date_format($"log_dt", "S"))
更新:Java 8 的 LocalDateTime 微秒
//Imports
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
/* //Commented as per comment about IntelliJ
spark.udf.register("date_microsec", (dt: String) =>
val dtFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.n")
LocalDateTime.parse(dt, dtFormatter).getLong(ChronoField.MICRO_OF_SECOND)
)
*/
import org.apache.spark.sql.functions.udf
val date_microsec = udf((dt: String) => {
val dtFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.n")
LocalDateTime.parse(dt, dtFormatter).getLong(ChronoField.MICRO_OF_SECOND)
})
使用 ChronoField.NANO_OF_SECOND
而不是 ChronoField.MICRO_OF_SECOND
在 UDF 中获取纳秒.
Use ChronoField.NANO_OF_SECOND
instead of ChronoField.MICRO_OF_SECOND
to fetch Nanosecond in UDF.
val df = tablereader1Df.withColumn("log_date_microsec", date_microsec($"log_dt"))
这篇关于在 Spark Scala 中处理微秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!