如何在spark scala中的数据框列中验证日期格式 [英] How to validate date format in a dataframe column in spark scala
问题描述
我想要做的是解析这个datetime列值,并检查格式是否为yyyy -MM-dd HH:mm:ss。如果是这样,那么我希望在一个数据框中使用这些有效的记录。
如果datetime列中包含格式yyyy-MM-dd HH:mm:ss 。我想在另一个数据框中使用这些无效记录。
谢谢。
p>您可以使用 filter()
获取数据框中的有效/无效
记录。这个代码可以用scala的观点来改进。
val DATE_TIME_FORMAT =yyyy-MM-dd HH:mm:ss
def validateDf(row:Row):Boolean = try {
//假设row.getString(1)与给定Datetime字符串
java.time.LocalDateTime.parse(row .getString(1),java.time.format.DateTimeFormatter.ofPattern(DATE_TIME_FORMAT))
true
} catch {
case ex:java.time.format.DateTimeParseException => {
//处理异常如果你想要
false
}
}
val session = SparkSession.builder
.appName(验证数据框)
.getOrCreate
val df = session。 .... //从任何数据源读取
import session.implicits._ // implicits提供except()在df
val validDf = df.filter(validateDf _))
val inValidDf = df.except(validDf)
I have a dataframe with one datetime column and many other columns.
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.
If the datetime column holds any value other than format "yyyy-MM-dd HH:mm:ss". I wanted those invalid records in an other dataframe.
Thanks.
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屋!