【问题标题】:getting the current timestamp of each row of dataframe using Spark / Java使用 Spark/Java 获取每行数据帧的当前时间戳
【发布时间】:2020-10-27 21:56:23
【问题描述】:

我想获取每一行的当前时间戳。

我使用下面的代码

dataframe.withColumn("current_date",current_timestamp());

但是 current_timestamp() 是在序列化之前评估的,所以我总是会得到相同的日期。

如何评估每行数据帧的 current_timestamp()。

我需要你的帮助。

谢谢。

【问题讨论】:

    标签: java dataframe apache-spark current-time


    【解决方案1】:

    试试这个 -

    
        df2.withColumn("current_date", expr("reflect('java.lang.System', 'currentTimeMillis')"))
          .show(false)
    
        /**
          * +-----+------+-------------+
          * |class|gender|current_date |
          * +-----+------+-------------+
          * |1    |m     |1594137247247|
          * |1    |m     |1594137247247|
          * |1    |f     |1594137247247|
          * |2    |f     |1594137247272|
          * |2    |f     |1594137247272|
          * |3    |m     |1594137247272|
          * |3    |m     |1594137247272|
          * +-----+------+-------------+
          */
    
        df2.withColumn("current_date", expr("reflect('java.time.LocalDateTime', 'now')"))
          .show(false)
    
        /**
          * +-----+------+-----------------------+
          * |class|gender|current_date           |
          * +-----+------+-----------------------+
          * |1    |m     |2020-07-07T21:24:07.377|
          * |1    |m     |2020-07-07T21:24:07.378|
          * |1    |f     |2020-07-07T21:24:07.378|
          * |2    |f     |2020-07-07T21:24:07.398|
          * |2    |f     |2020-07-07T21:24:07.398|
          * |3    |m     |2020-07-07T21:24:07.398|
          * |3    |m     |2020-07-07T21:24:07.398|
          * +-----+------+-----------------------+
          */
    // you can convert current_date to timestamp by casting it to "timestamp"
    

    【讨论】:

      【解决方案2】:

      即使是直接的python表达式也被视为序列化时间常数,下面的代码也为每一行给出相同的时间值,

      dataframe.withColumn("current_date", F.lit( time.time()))
      

      但是为时间值制作一个UDF使其在运行时解析时间值,如下所示,

      from pyspark.sql.functions import udf
      
      def get_time():
          return time.time()
      
      time_udf=udf(get_time)
      
      dataframe.withColumn("current_date", time_udf())
      

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-04
        • 1970-01-01
        • 2020-01-23
        • 2019-07-21
        • 1970-01-01
        • 2012-01-10
        • 2011-12-26
        相关资源
        最近更新 更多