Are you looking to find out how to get the number of days between two days of PySpark DataFrame using Azure Databricks cloud or maybe you are looking for a solution, to get difference between two days from date columns in PySpark Databricks using the datediff() function? If you are looking for any of these problem solutions, you have landed on the correct page. I will also help you how to use PySpark datediff() function with multiple examples in Azure Databricks. I will explain it by taking a practical example. So please don’t waste time let’s start with a step-by-step guide to understand how to use the datediff() function in PySpark.
In this blog, I will teach you the following with practical examples:
- Syntax of datediff()
- Date difference using DataFrame
- Date difference using SQL expression
The Pyspark datediff() function is used to get the number of days between from and to date.
Syntax:
datediff()
Contents
- 1 What is the syntax of the datediff() function in PySpark Azure Databricks?
- 2 Create a simple DataFrame
- 3 How to find the number of days in between dates in PySpark Azure Databricks?
- 4 How to find the number of days in between dates in PySpark Azure Databricks using SQL expression?
- 5 When should you use the PySpark datediff() in Azure Databricks?
- 6 Real World Use Case Scenarios for PySpark DataFrame datediff() in Azure Databricks?
- 7 What are the alternatives to the datediff() function in PySpark Azure Databricks?
- 8 Final Thoughts
What is the syntax of the datediff() function in PySpark Azure Databricks?
The syntax is as follows:
datediff(end_date, start_date)
Parameter Name | Required | Description |
end_date (str, Column) | Yes | It represents the ending date. |
start_date (str, Column) | Yes | It represents the starting date. |
Apache Spark Official Documentation Link: datediff()
Note: PySpark’s DateTime function supports both DataFrame and SQL work, very similar to traditional SQL. If you work with data extraction, transformation, and loading, you should have a good understanding of SQL Date functions.
Create a simple DataFrame
Let’s understand the use of the datediff() function with various examples. Let’s start by creating a DataFrame.
Gentle reminder:
In Databricks,
- sparkSession made available as spark
- sparkContext made available as sc
In case, you want to create it manually, use the below code.
from pyspark.sql.session import SparkSession
spark = SparkSession.builder
.master("local[*]")
.appName("azurelib.com")
.getOrCreate()
sc = spark.sparkContext
a) Create manual PySpark DataFrame
data = [
("2019-01-11","2021-04-12","2019-09-17 12:02:21","2021-07-12 18:29:29"),
("2019-08-04","2021-04-15","2018-11-11 14:17:05","2021-08-03 16:21:40"),
("2019-03-24","2021-02-08","2019-02-07 04:26:49","2020-11-28 05:20:33"),
("2019-04-13","2021-06-05","2019-07-08 20:04:09","2021-05-18 08:21:12"),
("2019-02-22","2021-10-01","2018-11-28 05:46:54","2021-06-17 21:39:42")
]
columns = ["from_date","to_date","from_datetime","to_datetime"]
df = spark.createDataFrame(data, schema=columns)
df.printSchema()
df.show(truncate=False)
"""
root
|-- from_date: string (nullable = true)
|-- to_date: string (nullable = true)
|-- from_datetime: string (nullable = true)
|-- to_datetime: string (nullable = true)
+----------+----------+-------------------+-------------------+
|from_date |to_date |from_datetime |to_datetime |
+----------+----------+-------------------+-------------------+
|2019-01-11|2021-04-12|2019-09-17 12:02:21|2021-07-12 18:29:29|
|2019-08-04|2021-04-15|2018-11-11 14:17:05|2021-08-03 16:21:40|
|2019-03-24|2021-02-08|2019-02-07 04:26:49|2020-11-28 05:20:33|
|2019-04-13|2021-06-05|2019-07-08 20:04:09|2021-05-18 08:21:12|
|2019-02-22|2021-10-01|2018-11-28 05:46:54|2021-06-17 21:39:42|
+----------+----------+-------------------+-------------------+
"""
b) Creating a DataFrame by reading files
Download and use the below source file.
# replace the file_path with the source file location which you have downloaded.
df_2 = spark.read.format("csv").option("header", True).load(file_path)
df_2.printSchema()
"""
root
|-- from_date: string (nullable = true)
|-- to_date: string (nullable = true)
|-- from_datetime: string (nullable = true)
|-- to_datetime: string (nullable = true)
"""
Note: Here, I will be using the manually created DataFrame.
How to find the number of days in between dates in PySpark Azure Databricks?
Let’s see how to find the difference between days in PySpark using Azure Databricks.
Example 1:
# using select()
from pyspark.sql.functions import datediff
df.select("from_date", datediff("to_date", "from_date").alias("difference"), "to_date").show()
"""
Output:
+----------+----------+----------+
| from_date|difference| to_date|
+----------+----------+----------+
|2019-01-11| 822|2021-04-12|
|2019-08-04| 620|2021-04-15|
|2019-03-24| 687|2021-02-08|
|2019-04-13| 784|2021-06-05|
|2019-02-22| 952|2021-10-01|
+----------+----------+----------+
"""
Example 2:
# using withColumn()
from pyspark.sql.functions import datediff
df.withColumn("difference", datediff("to_datetime", "from_datetime")) \
.select("to_datetime", "difference", "from_datetime").show()
"""
Output:
+-------------------+----------+-------------------+
| to_datetime|difference| from_datetime|
+-------------------+----------+-------------------+
|2021-07-12 18:29:29| 664|2019-09-17 12:02:21|
|2021-08-03 16:21:40| 996|2018-11-11 14:17:05|
|2020-11-28 05:20:33| 660|2019-02-07 04:26:49|
|2021-05-18 08:21:12| 680|2019-07-08 20:04:09|
|2021-06-17 21:39:42| 932|2018-11-28 05:46:54|
+-------------------+----------+-------------------+
"""
How to find the number of days in between dates in PySpark Azure Databricks using SQL expression?
Let’s see how to the difference between days using SQL expressions in PySpark Azure Databricks.
Example:
In order to use raw SQL expression, we have to convert our Dataframe into SQL view.
df.createOrReplaceTempView("days")
spark.sql("""
SELECT
from_date,
floor(datediff(to_date, from_date)) AS difference,
to_date
FROM days
""").show()
"""
Output:
+----------+----------+----------+
| from_date|difference| to_date|
+----------+----------+----------+
|2019-01-11| 822|2021-04-12|
|2019-08-04| 620|2021-04-15|
|2019-03-24| 687|2021-02-08|
|2019-04-13| 784|2021-06-05|
|2019-02-22| 952|2021-10-01|
+----------+----------+----------+
"""
I have attached the complete code used in this blog in notebook format to this GitHub link. You can download and import this notebook in databricks, jupyter notebook, etc.
When should you use the PySpark datediff() in Azure Databricks?
These could be the possible reasons:
- To find the days difference between the Date format
- To find the days difference between the DateTime format
Real World Use Case Scenarios for PySpark DataFrame datediff() in Azure Databricks?
Assume that you have an employee dataset. The dataset has the employee’s ID, name, starting_date, and ending_date. You have been given a requirement to find out the number of months employees have been working in your organization. You can use the PySpark datediff() inbuilt function to find out the number of days in-between dates.
What are the alternatives to the datediff() function in PySpark Azure Databricks?
The PySpark function datediff() is the only one that helps in finding the number of days between two dates and this function is explained in detail in the above section with multiple examples.
Final Thoughts
In this article, we have learned about the PySpark datediff() method of DataFrame in Azure Databricks along with the examples explained clearly. I have also covered different scenarios with practical examples that could be possible. I hope the information that was provided helped in gaining knowledge.
Please share your comments and suggestions in the comment section below and I will try to answer all your queries as time permits.
- For Azure Study material Join Telegram group : Telegram group link:
- Azure Jobs and other updates Follow me on LinkedIn: Azure Updates on LinkedIn
- Azure Tutorial Videos: Videos Link
- Azure Databricks Lesson 1
- Azure Databricks Lesson 2
- Azure Databricks Lesson 3
- Azure Databricks Lesson 4
- Azure Databricks Lesson 5
- Azure Databricks Lesson 6
- Azure Databricks Lesson 7
As a big data engineer, I design and build scalable data processing systems and integrate them with various data sources and databases. I have a strong background in Python and am proficient in big data technologies such as Hadoop, Hive, Spark, Databricks, and Azure. My interest lies in working with large datasets and deriving actionable insights to support informed business decisions.