如何从csv文件中以自定义格式读取日期? [英] How to read date in custom format from csv file?
问题描述
我正在解析一个数据为
03-10-2016,18:00:00,2,6
当我阅读如下文件创建模式时
When I am reading file creating schema as below
StructType schema = DataTypes.createStructType(Arrays.asList(
DataTypes.createStructField("Date", DataTypes.DateType, false),
DataTypes.createStructField("Time", DataTypes.TimestampType, false),
DataTypes.createStructField("CO(GT)", DataTypes.IntegerType, false),
DataTypes.createStructField("PT08.S1(CO)", DataTypes.IntegerType, false)))
Dataset<Row> df = spark.read().format("csv").option("Date", "dd-MM-yyyy").schema(schema).load("src/main/resources/AirQualityUCI/sample.csv");
它产生的错误如下
Exception in task 0.0 in stage 0.0 (TID 0)
java.lang.IllegalArgumentException
at java.sql.Date.valueOf(Unknown Source)
at org.apache.spark.sql.catalyst.util.DateTimeUtils$.stringToTime(DateTimeUtils.scala:137)
我认为这是由于日期格式错误所致.将它们转换为特定格式的方法是什么?
I feel that it is due to date format error. What are the ways of converting them into specific formats?
推荐答案
读取CSV文件时,请使用dateFormat
选项,如下所示:
Use dateFormat
option when reading the CSV file(s) as follows:
val csvs = spark.
read.
format("csv").
option("dateFormat", "dd-MM-yyyy"). // <-- should match 03-10-2016
load(...)
dateFormat
的默认值为yyyy-MM-dd
,因此解析错误也就不足为奇了.
The default for dateFormat
is yyyy-MM-dd
so it's no surprise you've got the parsing error.
引用 valueOf :
抛出
IllegalArgumentException
-如果给定的日期不是JDBC日期转义格式(yyyy- [m] m- [d] d)
Throws
IllegalArgumentException
- if the date given is not in the JDBC date escape format (yyyy-[m]m-[d]d)
这意味着该值对于valueOf
的解析器而言是不正确的.
That means that the value is incorrect for the parser of valueOf
.
我在这里有两个建议:
-
读取数据集并
show
看看里面有什么.
使用dateFormat
选项定义正确的格式(默认为yyyy-MM-dd
)
Use dateFormat
option to define the proper format (it's yyyy-MM-dd
by default)
在日期和时间模式(属于java.text.SimpleDateFormat
).
这篇关于如何从csv文件中以自定义格式读取日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!