处理Spark Scala中的微秒
我使用Scala将PostgreSQL表作为dataframe导入spark。 数据框看起来像
user_id | log_dt --------| ------- 96 | 2004-10-19 10:23:54.0 1020 | 2017-01-12 12:12:14.931652
我正在转换此dataframe,使log_dt的数据格式为yyyy-MM-dd hh:mm:ss.SSSSSS
。 为了实现这一点,我使用以下代码使用unix_timestamp
函数将log_dt转换为时间戳格式。
val tablereader1=tablereader1Df.withColumn("log_dt",unix_timestamp(tablereader1Df("log_dt"),"yyyy-MM-dd hh:mm:ss.SSSSSS").cast("timestamp"))
当我打印使用命令tablereader1.show()
打印tablereader1dataframe时,我得到以下结果
user_id | log_dt --------| ------- 96 | 2004-10-19 10:23:54.0 1020 | 2017-01-12 12:12:14.0
如何将微秒保留为时间戳的一部分? 任何建议表示赞赏。
使用date_format()
千字节数
您可以使用接受Java SimpleDateFormat模式的Spark SQL date_format()
。 SimpleDateFormat
只能使用模式“S”解析直到milleseconds。
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) })
检查: 帮助构建DateTimeFormatter模式
使用ChronoField.NANO_OF_SECOND
而不是ChronoField.MICRO_OF_SECOND
在UDF中获取纳秒。
val df = tablereader1Df.withColumn("log_date_microsec", date_microsec($"log_dt"))