如何验证spark scala中数据框列中的日期格式 [英] How to validate date format in a dataframe column in spark scala
问题描述
我有一个包含一个 DateTime 列和许多其他列的数据框.
I have a dataframe with one DateTime column and many other columns.
我想要做的就是解析这个 DateTime 列值并检查格式是否为 "yyyy-MM-dd HH:mm:ss"
.如果是这样,那么我希望将这些有效记录放在一个数据框中.
All I wanted to do is parse this DateTime column value and check if the format is "yyyy-MM-dd HH:mm:ss"
. If so, then I wanted these valid records in one dataframe.
如果 DateTime 列包含格式 "yyyy-MM-dd HH:mm:ss"
以外的任何值.我想要其他数据框中的那些无效记录.
If the DateTime column holds any value other than format "yyyy-MM-dd HH:mm:ss"
. I wanted those invalid records in the other dataframe.
谢谢.
推荐答案
您可以使用 filter()
来获取 dataframe 中的 valid/invalid
记录.从 Scala 的角度来看,此代码可以改进.
You can use filter()
to get the valid/invalid
records in dataframe. This code can be improvable with scala point of view.
val DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"
def validateDf(row: Row): Boolean = try {
//assume row.getString(1) with give Datetime string
java.time.LocalDateTime.parse(row.getString(1), java.time.format.DateTimeFormatter.ofPattern(DATE_TIME_FORMAT))
true
} catch {
case ex: java.time.format.DateTimeParseException => {
// Handle exception if you want
false
}
}
val session = SparkSession.builder
.appName("Validate Dataframe")
.getOrCreate
val df = session. .... //Read from any datasource
import session.implicits._ //implicits provide except() on df
val validDf = df.filter(validateDf(_))
val inValidDf = df.except(validDf)
这篇关于如何验证spark scala中数据框列中的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!