在两个给定时间戳之间创建时间序列(范围)

Posted

技术标签:

【中文标题】在两个给定时间戳之间创建时间序列(范围)【英文标题】:Create timeseries (range) between two given timestamp 【发布时间】:2020-08-28 11:54:51 【问题描述】:

我有一个 pyspark 数据框 df

---------------------------------------------------------
primaryKey |   start_timestamp   |   end_timestamp
---------------------------------------------------------
 key1      | 2020-08-13 15:40:00 | 2020-08-13 15:44:47
 key2      | 2020-08-14 12:00:00 | 2020-08-14 12:01:13

我想创建一个数据帧,它的时间序列在 start_timestamp 和 end_timestamp 之间,所有键的间隔为 x 秒。 例如,对于 x = 120 秒的间隙,输出将是:-

-----------------------------------------------------------
primaryKey |  start_timestamp_new  | end_timestamp_new
   key1    |  2020-08-13 15:40:00  | 2020-08-13 15:41:59
   key1    |  2020-08-13 15:42:00  | 2020-08-13 15:43:59
   key1    |  2020-08-13 15:44:00  | 2020-08-13 15:45:59
   key2    |  2020-08-14 12:00:00  | 2020-08-14 12:01:59

我正在尝试使用提到的方法here,但无法将其应用于 spark 数据帧。

任何有关创建它的信息都会有很大帮助。

【问题讨论】:

【参考方案1】:

你可以使用sequence函数。

x = 120

df.withColumn('start_timestamp', to_timestamp('start_timestamp')) \
  .withColumn('end_timestamp', to_timestamp('end_timestamp')) \
  .withColumn('start_timestamp', explode(sequence('start_timestamp', 'end_timestamp', expr(f'interval x seconds')))) \
  .withColumn('end_timestamp', col('start_timestamp') + expr(f'interval x - 1 seconds')) \
  .show()

+----------+-------------------+-------------------+
|primaryKey|    start_timestamp|      end_timestamp|
+----------+-------------------+-------------------+
|      key1|2020-08-13 15:40:00|2020-08-13 15:41:59|
|      key1|2020-08-13 15:42:00|2020-08-13 15:43:59|
|      key1|2020-08-13 15:44:00|2020-08-13 15:45:59|
|      key2|2020-08-14 12:00:00|2020-08-14 12:01:59|
+----------+-------------------+-------------------+

【讨论】:

那么我应该在时间列上使用前导窗口函数吗?为了获得所需输出中的数据? 不,只需添加 x-1 你能帮我解决这个问题吗 - ***.com/questions/66000491/…

以上是关于在两个给定时间戳之间创建时间序列(范围)的主要内容,如果未能解决你的问题,请参考以下文章