Spark Version: spark-2.0.1-bin-hadoop2.7
Scala: 2.11.8
我正在将原始 csv 加载到 DataFrame 中。在 csv 中,虽然该列支持日期格式,但它们被写为 20161025 而不是 2016-10-25。该参数date_format
包括需要转换为 yyyy-mm-dd 格式的列名字符串。
在下面的代码中,我首先通过 将 Date 列的 csv 加载为 StringType schema
,然后检查 是否date_format
不为空,即有需要转换为Date
from的列,然后使用and转换String
每一列。但是,在 中,返回的行都是. unix_timestamp
to_date
csv_df.show()
null
def read_csv(csv_source:String, delimiter:String, is_first_line_header:Boolean,
schema:StructType, date_format:List[String]): DataFrame = {
println("|||| Reading CSV Input ||||")
var csv_df = sqlContext.read
.format("com.databricks.spark.csv")
.schema(schema)
.option("header", is_first_line_header)
.option("delimiter", delimiter)
.load(csv_source)
println("|||| Successfully read CSV. Number of rows -> " + csv_df.count() + " ||||")
if(date_format.length > 0) {
for (i <- 0 until date_format.length) {
csv_df = csv_df.select(to_date(unix_timestamp(
csv_df(date_format(i)), "yyyy-MM-dd").cast("timestamp")))
csv_df.show()
}
}
csv_df
}
返回前 20 行:
+-------------------------------------------------------------------------+
|to_date(CAST(unix_timestamp(prom_price_date, YYYY-MM-DD) AS TIMESTAMP))|
+-------------------------------------------------------------------------+
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
+-------------------------------------------------------------------------+
为什么我得到所有null
?