I am dealing with a problem in PySpark.
Input:
+-------+---------------------+
|user_id|activity_timestamp |
+-------+---------------------+
| 1| 2021/06/01 19:00 |
| 1| 2021/06/01 19:01 |
| 2| 2021/06/01 19:01 |
| 1| 2021/06/01 19:02 |
| 2| 2021/06/01 19:02 |
| 1| 2021/06/01 19:10 |
| 1| 2021/06/01 19:11 |
+-------+---------------------+
Desired output: For each user, detect periods of continuous activity timestamp (gaps between timestamps are smaller than for ex. 5 minutes)
+-------+---------------------------+---------------------------+
|user_id| activity _start | activity _stop |
+-------+---------------------------+---------------------------+
| 1| 2021/06/01 19:00 | 2021/06/01 19:02 |
| 1| 2021/06/01 19:10 | 2021/06/01 19:11 |
| 2| 2021/06/01 19:01 | 2021/06/01 19:02 |
Progress so far: I have used a Window function to find the time of the previous activity and from that I have calculated the time that passed since previous activity. But I am struggling to create the desired output.
time_window = Window.partitionBy("user_id").orderBy("user_id", "activity_timestamp")
df = (df
.withColumn('prev_time', F.lag(F.col('activity_timestamp')).over(time_window))
.withColumn('time_gap', F.col('activity_timestamp').cast("long") - F.col('prev_time').cast("long"))
)