from pyspark.sql import SparkSession
from pyspark.sql import functions as F
# Create PySpark dataframe
columns = ["user","hiring_date","termination_date"]
data = [("A", "1995-09-08", "1997-09-09"), ("A", "2003-05-08", "2006-11-09"),
("A", "2000-05-06", "2003-05-09"), ("B", "2007-06-27", "2008-05-27"),
("C", "2003-01-20", "2006-01-19"), ("C", "2011-04-03", "2011-04-04")]
spark = SparkSession.builder.appName('SparkByExamples.com').getOrCreate()
rdd = spark.sparkContext.parallelize(data)
df = spark \
.createDataFrame(rdd) \
.toDF(*columns) \
.withColumn('hiring_date', F.expr('CAST(hiring_date AS DATE)')) \
.withColumn('termination_date', F.expr('CAST(termination_date AS DATE)'))
df.show()
+----+-----------+----------------+
|user|hiring_date|termination_date|
+----+-----------+----------------+
| A| 1995-09-08| 1997-09-09|
| A| 2003-05-08| 2006-11-09|
| A| 2000-05-06| 2003-05-09|
| B| 2007-06-27| 2008-05-27|
| C| 2003-01-20| 2006-01-19|
| C| 2011-04-03| 2011-04-04|
+----+-----------+----------------+
In the above example, I have multiple users with a start date hiring_date and an end date termination_date. Per user, there can be single as well as multiple rows. In addition, users can have multiple jobs at the same time (overlapping termination and hiring dates).
For each user, I need to calculate the following:
- The number of days the user was working. Overlapping dates should not be counted multiple times.
- The number of days the user was not working (i.e., was on vacation).



