将列类型从字符串更改为日期

将列类型从字符串更改为日期

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

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

  • 当我尝试应用链接1的答案时,结果却为空,因此我引用了链接2的答案,但我不理解这一部分:
    output_format = ...  # Some SimpleDateFormat string
    

    我想直接从评论中询问,但是,我的声誉还不够。

    最佳答案

    希望这可以帮助!

    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)
    

    关于python - 在Pyspark中将列类型从字符串更改为日期,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47953320/

    10-09 06:20