【问题标题】:Change column type from string to date in Pyspark在 Pyspark 中将列类型从字符串更改为日期
【发布时间】:2017-12-23 14:32:09
【问题描述】:

我正在尝试将我的列类型从字符串更改为日期。我咨询了以下人员的答案:

  1. How to change the column type from String to Date in DataFrames?
  2. Why I get null results from date_format() PySpark function?

当我尝试应用链接 1 中的答案时,我得到了 null 结果,所以我参考了链接 2 中的答案,但我不明白这部分:

output_format = ...  # Some SimpleDateFormat string

【问题讨论】:

    标签: python pyspark


    【解决方案1】:
    from pyspark.sql.functions import col, unix_timestamp, to_date
    
    #sample data
    df = sc.parallelize([['12-21-2006'],
                         ['05-30-2007'],
                         ['01-01-1984'],
                         ['12-24-2017']]).toDF(["date_in_strFormat"])
    df.printSchema()
    
    df = df.withColumn('date_in_dateFormat', 
                       to_date(unix_timestamp(col('date_in_strFormat'), 'MM-dd-yyyy').cast("timestamp")))
    df.show()
    df.printSchema()
    

    输出是:

    root
     |-- date_in_strFormat: string (nullable = true)
    
    +-----------------+------------------+
    |date_in_strFormat|date_in_dateFormat|
    +-----------------+------------------+
    |       12-21-2006|        2006-12-21|
    |       05-30-2007|        2007-05-30|
    |       01-01-1984|        1984-01-01|
    |       12-24-2017|        2017-12-24|
    +-----------------+------------------+
    
    root
     |-- date_in_strFormat: string (nullable = true)
     |-- date_in_dateFormat: date (nullable = true)
    

    【讨论】:

    • 天哪,这有帮助,但只是部分帮助 :( 一些日期仍然返回空值。就像只有一些被转换?
    • 您需要检查字符串列中的日期格式。它应该在MM-dd-yyyy 中,否则它将返回null
    • 我的日期的原始字符串写在 dd/MM/yyyy 中。我在您编写的代码中使用了它,就像我说的那样,只有一些被转换为日期类型......
    【解决方案2】:

    简单的方法:

    from pyspark.sql.types import *
    df_1 = df.withColumn("col_with_date_format",
    df["col_with_date_format"].cast(DateType()))
    

    【讨论】:

      【解决方案3】:

      这是使用默认 to_date 函数的更简单的方法:

      from pyspark.sql import functions as F
      df= df.withColumn('col_with_date_format',F.to_date(df.col_with_str_format))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-25
        • 1970-01-01
        • 2021-02-27
        • 1970-01-01
        • 2020-08-15
        • 2021-11-19
        • 1970-01-01
        • 2018-04-09
        相关资源
        最近更新 更多