【问题标题】:How to add Extra column with current date in Spark dataframe如何在 Spark 数据框中添加具有当前日期的额外列
【发布时间】:2020-09-09 13:57:39
【问题描述】:

我正在尝试使用 withColumn 方法在我现有的 Pyspark 数据框中添加一列。我想在此列中插入当前日期。从我的源中我没有任何日期列,所以我在我的数据框并将此数据框保存在我的表中,以便稍后出于跟踪目的,我可以使用此当前日期列。 我正在使用以下代码

    df2=df.withColumn("Curr_date",datetime.now().strftime('%Y-%m-%d'))

这里 df 是我现有的数据框,我想将 df2 保存为带有 Curr_date 列的表。 但这里它期望现有的列或点亮方法而不是 datetime.now().strftime('%Y-%m-%d')。 有人请指导我如何在我的数据框中添加此日期列。?

【问题讨论】:

    标签: dataframe apache-spark pyspark apache-spark-sql


    【解决方案1】:

    使用litcurrent_date

    from pyspark.sql import functions as F
    
    df2 = df.withColumn("Curr_date", F.lit(datetime.now().strftime("%Y-%m-%d")))
    
    # OR
    
    df2 = df.withColumn("Curr_date", F.current_date())
    

    【讨论】:

      【解决方案2】:

      current_timestamp() 很好,但在序列化期间会对其进行评估。

      如果你更喜欢使用timestamp的处理时间的一行,那么你可以使用下面的方法,

      withColumn('current', expr("reflect('java.time.LocalDateTime', 'now')"))
      

      【讨论】:

        【解决方案3】:

        有一个spark函数current_timestamp()

        from pyspark.sql.functions import *
        
        df.withColumn('current', date_format(current_timestamp(), 'yyyy-MM-dd')).show()
        
        +----+----------+
        |test|   current|
        +----+----------+
        |test|2020-09-09|
        +----+----------+
        
        

        【讨论】:

          猜你喜欢
          • 2021-12-27
          • 2018-07-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-11
          • 1970-01-01
          • 1970-01-01
          • 2023-02-08
          • 2016-03-06
          相关资源
          最近更新 更多