【问题标题】:convert string to date (format year quarter) in pyspark在pyspark中将字符串转换为日期(格式年季度)
【发布时间】:2020-04-24 00:18:55
【问题描述】:

我有一个带有列的以下数据框:

df

id dt
1  2016/2017 Q2
2  2017/2018 Q1
3  2018/2019 Q2

输出:

df

id date
1  2016-07-01
2  2017-04-01
3  2018-07-01

我需要在 pyspark 中将它们转换为日期 通常,我使用下面的代码通过指定格式来转换为日期,但找不到季度的任何格式,请您指教。

代码:F.from_unixtime(F.unix_timestamp(date_str, fmt)).cast("date")

【问题讨论】:

    标签: date pyspark


    【解决方案1】:

    我认为没有返回季度日期的直接函数/格式

    对于这种情况,我们需要使用when 语句(或)udf

    示例:

    df=spark.createDataFrame([("1","2016/2017 Q2"),("2","2017/2018 Q1"),("3","2018/2019 Q3"),("4","2019/2020 Q4")],["id","dt"])
    
    #4 quarters in an year
    df.withColumn("date",
        when(lower(reverse(split(col("dt")," "))[0]) == "q1",concat_ws("-",substring(col("dt"),0,4),lit("01-01")).cast("date")).\
        when(lower(reverse(split(col("dt")," "))[0]) == "q2",concat_ws("-",substring(col("dt"),0,4),lit("04-01")).cast("date")).\
        when(lower(reverse(split(col("dt")," "))[0]) == "q3",concat_ws("-",substring(col("dt"),0,4),lit("07-01")).cast("date")).\
        when(lower(reverse(split(col("dt")," "))[0]) == "q4",concat_ws("-",substring(col("dt"),0,4),lit("10-01")).cast("date")).\
        otherwise(lit("Quarter not found"))).show()
    
    #+---+------------+----------+
    #| id|          dt|      date|
    #+---+------------+----------+
    #|  1|2016/2017 Q2|2016-04-01|
    #|  2|2017/2018 Q1|2017-01-01|
    #|  3|2018/2019 Q3|2018-07-01|
    #|  4|2019/2020 Q4|2019-10-01|
    #+---+------------+----------+
    

    【讨论】:

      猜你喜欢
      • 2015-09-13
      • 2020-06-24
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 2016-10-31
      • 1970-01-01
      • 1970-01-01
      • 2021-07-25
      相关资源
      最近更新 更多