如何在spark的csv文件中加载dd/mm/yyyy格式的日期?

lf3rwulv  于 2021-05-27  发布在  Spark
关注(0)|答案(1)|浏览(478)

环境:spark 2.4.5
我有一个要加载的.csv文件,其中的日期格式为“dd/mm/yyyy”,但spark可能无法正确加载此格式的日期。
我试过这些功能: 'to_date()', 'to_timestamp()', 'unix_timestamp()' ,但它们都返回具有此格式日期的“null”。如果你能给我一些建议,我将不胜感激。

9q78igpj

9q78igpj1#

dateFormat –设置表示日期格式的字符串。自定义日期格式遵循java.text.simpleDataFormat中的格式。这适用于日期类型。如果未设置,则使用默认值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>

相关问题