如何在火花的csv文件中加载"dd / MM / yyyy"格式的日期?



env: Spark 2.4.5

我有一个要加载.csv文件,其中的日期格式为"dd/MM/yyyy",但 Spark 可能无法正确加载此格式日期。

我已经尝试了这些函数:'to_date()', 'to_timestamp()', 'unix_timestamp()',但它们都以这种格式日期返回"null"。如果您能给我一些建议,我将不胜感激。

dateFormat– 设置指示日期格式的字符串。自定义日期格式遵循 java.text.SimpleDateFormat 中的格式。这适用于日期类型。如果设置了"无",则使用默认值 yyyy-MM-dd

尝试添加此选项 -option("dateFormat", "dd/MM/yyyy")解析 CSV 文件中的日期列。

CSV 文件数据

scala> "cat /tmp/sample.csv".!
"id","dt"
1,01/05/2020
2,20/04/2020
scala> val schema = DataType.fromJson("""{"type":"struct","fields":[{"name":"id","type":"integer","nullable":true,"metadata":{}},{"name":"dt","type":"date","nullable":true,"metadata":{}}]}""").asInstanceOf[StructType]
schema: org.apache.spark.sql.types.StructType = StructType(StructField(id,IntegerType,true), StructField(dt,DateType,true))
scala> schema.prettyJson
res26: String =
{
"type" : "struct",
"fields" : [ {
"name" : "id",
"type" : "integer",
"nullable" : true,
"metadata" : { }
}, {
"name" : "dt",
"type" : "date",
"nullable" : true,
"metadata" : { }
} ]
}
scala> val df = spark
.read
.option("header","true")
.option("dateFormat", "dd/MM/yyyy") // add this to parse date values from csv file.
.schema(schema)
.format("csv").load("/tmp/sample.csv")
df: org.apache.spark.sql.DataFrame = [id: int, dt: date]
scala> df.show(false)
+---+----------+
|id |dt        |
+---+----------+
|1  |2020-05-01|
|2  |2020-04-20|
+---+----------+

scala>

最新更新