【问题标题】:Spark / Databricks Code not recognizing date field errorSpark / Databricks 代码无法识别日期字段错误
【发布时间】:2019-09-30 08:32:10
【问题描述】:

我正在查询我已转换为 datetype 的 spark 数据框中的 col:

SAlesByCountry2 = SAlesByCountry.withColumn("SaleDate", current_date())

转换成功见下图:

SAlesByCountry2:pyspark.sql.dataframe.DataFrame
CountryName:string
MakeName:string
ModelName:string
Cost:integer
RepairsCost:integer
PartsCost:string
TransportInCost:integer
Color:string
SalePrice:double
LineItemDiscount:string
InvoiceNumber:string
SaleDate:date
CustomerName:string
SalesDetailsID:integer`

但是,当我使用以下 sql 代码查询数据框时:

SELECT
  *
FROM SAlesByCountry2
WHERE YEAR(SAlesByCountry2.SaleDate) = 2018

我没有得到任何数据,见下文

即使当我查询整个数据框时确实存在 2018 年

这非常令人费解,因为它应该只是显示数据,但我不明白为什么没有数据显示日期为 2018 年

【问题讨论】:

    标签: apache-spark apache-spark-sql azure-databricks


    【解决方案1】:

    您的代码中有很多歧义。下面的语句不改变数据类型,它用今天的日期初始化值(所以在这种情况下,不可能获得 2018 年的数据)

    SAlesByCountry2 = SAlesByCountry.withColumn("SaleDate", current_date())
    

    我可以看到,在您现有的 dataframe 列中,SaleDate 的日期格式与返回的日期格式 current_date() 不同。 current_date() 返回日期格式为 yyyy-MM-dd 但您有 dd/MM/yyyy 的数据,其中 year 函数不起作用。

    scala> df.withColumn("SaleDate",  current_date()).select(col("SaleDate")).show
    +----------+
    |  SaleDate|
    +----------+
    |2019-09-30|
    |2019-09-30|
    |2019-09-30|
    |2019-09-30|
    |2019-09-30|
    |2019-09-30|
    +----------+
    

    year函数在您有日期格式为yyyy-MM-dd的数据时起作用。

     scala> df.withColumn("SaleDate",  date_format(current_date(), "dd/MM/yyyy")).filter(year(col("SaleDate")) === "2019").select(col("SaleDate")).show()
    +--------+
    |SaleDate|
    +--------+
    +--------+
    scala> df.withColumn("SaleDate",  date_format(current_date(), "yyyy-MM-dd")).filter(year(col("SaleDate")) === "2019").select(col("SaleDate")).show
    +----------+
    |  SaleDate|
    +----------+
    |2019-09-30|
    |2019-09-30|
    |2019-09-30|
    |2019-09-30|
    |2019-09-30|
    |2019-09-30|
    +----------+
    

    因此,对于您的问题的解决方案,您需要将SaleDate 列中的日期格式更改为yyyy-MM-dd,如下所示,并确认SaleDate 列对所有行都有唯一的格式。

     df.withColumn("SaleDate" , date_format(to_date(col("SaleDate"), "dd/MM/yyyy"), "yyyy-MM-dd")).filter(year(col("SaleDate")) === "2018")
    

    【讨论】:

      猜你喜欢
      • 2018-06-10
      • 2021-05-20
      • 1970-01-01
      • 2016-10-20
      • 1970-01-01
      • 2020-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多