Date functions

Spark tutorial · PySpark.in

Date and Time Functions: current_date, date_add, datediff, to_date, year, month

Overview: Dates and times are critical in many datasets (think transaction dates, sign-up dates, etc.). PySpark offers numerous functions to handle dates and times. Here we focus on common date functions:

These functions allow you to manipulate dates, such as computing future or past dates, measuring intervals, and extracting parts of dates for grouping or filtering.

Typical Use Cases:

Let's use an example of an employee hiring DataFrame to demonstrate these functions. We'll have a string column for hire date (as is common when data is read from CSV) which we'll convert to a date, and then use date functions.

Here hire_date_str is a string in format "yyyy-MM-dd". We will convert that to an actual date, then demonstrate date functions.

Converting String to Date with to_date

The to_date(col, format) function takes a string and a format and returns a DateType column. If the format is omitted, it tries to infer or uses the default 'yyyy-MM-dd' for casting. It's safer to provide the format if your string is in a known format.

Example: Convert hire_date_str to a date, and add today's date.

```

from pyspark.sql.functions import to_date, current_date,col

from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("BuiltInFuncDemo").getOrCreate()

hire_data = [

("Alice", "2022-01-10"),

("Bob", "2023-07-01"),

("Charlie", "2020-11-23"),

("Diana", "2023-02-20")

]

df_hire = spark.createDataFrame(hire_data, ["name", "hire_date_str"])

df_hire_dates = df_hire.withColumn("hire_date", to_date(col("hire_date_str"), "yyyy-MM-dd")) \

.withColumn("today", current_date())

df_hire_dates.select("name", "hire_date_str", "hire_date", "today").show()

```

We now have a proper hire_date (of type Date) and a today column (which is the current date when this was executed, for example it shows 2025-12-09 here). All calls to current_date() in the same query produce the same value, so every row has the same today.

Having hire_date as a DateType allows date arithmetic. If we kept it as string, Spark wouldn't know how to subtract or add days correctly.

Notice that to_date with the format "yyyy-MM-dd" worked directly on our string format. If the string was in a different format (say "01/10/2022"), we'd need to adjust the format accordingly (e.g., to_date(col, "MM/dd/yyyy")). If parsing fails or the string is not a valid date, to_date will result in NULL for that row.

Date Arithmetic with date_add and datediff

Now that we have date columns, we can perform arithmetic:

Example: Calculate a 90-day probation end date for each hire, and how many days have passed since hire.

```

from pyspark.sql.functions import date_add, datediff,col

from pyspark.sql.functions import to_date, current_date

from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("BuiltInFuncDemo").getOrCreate()

hire_data = [

("Alice", "2022-01-10"),

("Bob", "2023-07-01"),

("Charlie", "2020-11-23"),

("Diana", "2023-02-20")

]

df_hire_calc = df_hire_dates.withColumn("probation_end", date_add(col("hire_date"), 90)) \

.withColumn("days_since_hire", datediff(col("today"), col("hire_date")))

df_hire_calc.select("name", "hire_date", "probation_end", "days_since_hire").show()

```

Interpretation:

This shows date_add simply added 90 days (we could also subtract by using -90 if needed). The datediff(today, hire_date) gives how many days from hire to today. If we flipped it (hire_date, today) it would give negative values since hire_date is earlier; order matters.

Note: There are similar functions like date_sub (which is essentially date_add with negative days) and for timestamps there is add_months or months_between etc., but we stick to days here.

Extracting Year and Month

Often you want to group or filter by parts of dates. PySpark provides year(col) and month(col) to get the year and month as integers.

Example: Extract year and month of hire.

```

from pyspark.sql.functions import year, month

from pyspark.sql.functions import to_date, current_date,col

from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("BuiltInFuncDemo").getOrCreate()

hire_data = [

("Alice", "2022-01-10"),

("Bob", "2023-07-01"),

("Charlie", "2020-11-23"),

("Diana", "2023-02-20")

]

df_hire_calc.select("name", "hire_date", year(col("hire_date")).alias("hire_year"), month(col("hire_date")).alias("hire_month")).show()

```

We can see:

With these, you could, for example, group by hire_year to see hires per year, or filter where hire_month == 12 to find who was hired in December, etc.

Best Practices and Tips for Date Functions:

Working with dates correctly is crucial for analyses like retention (days since last login), cohorting (grouping by signup month/year), and so on. Spark's date functions help ensure these calculations are done correctly and efficiently on distributed data.

More Spark tutorials

All tutorials · Try the free PySpark compiler · Practice challenges