๐Ÿ“… Date & Time Functions

Almost every dataset has dates in it: order dates, sign-up times, event logs. Spark SQL has functions to parse dates from text, pull out parts like the month, add days, measure gaps between dates, and group data by week or month.

Every query below runs on Spark 3.5 and shows its exact result. The results were produced with the session time zone set to UTC.


1. Sample Data

This tutorial uses an orders view with a date column, a timestamp column, and a delivery date that is missing for one order:

CREATE OR REPLACE TEMP VIEW orders AS
SELECT * FROM VALUES
  (101, 'Asha', DATE'2024-01-15', TIMESTAMP'2024-01-15 09:30:00', DATE'2024-01-18', 250),
  (102, 'Ben',  DATE'2024-01-31', TIMESTAMP'2024-01-31 22:05:45', DATE'2024-02-03', 120),
  (103, 'Asha', DATE'2024-02-29', TIMESTAMP'2024-02-29 14:00:00', DATE'2024-03-05', 80),
  (104, 'Chen', DATE'2024-03-10', TIMESTAMP'2024-03-10 07:15:30', NULL,             310),
  (105, 'Ben',  DATE'2024-03-28', TIMESTAMP'2024-03-28 18:45:00', DATE'2024-04-02', 95)
AS orders(order_id, customer, order_date, order_ts, delivered_date, amount)
SELECT * FROM orders ORDER BY order_id
+--------+--------+----------+-------------------+--------------+------+
|order_id|customer|order_date|order_ts           |delivered_date|amount|
+--------+--------+----------+-------------------+--------------+------+
|101     |Asha    |2024-01-15|2024-01-15 09:30:00|2024-01-18    |250   |
|102     |Ben     |2024-01-31|2024-01-31 22:05:45|2024-02-03    |120   |
|103     |Asha    |2024-02-29|2024-02-29 14:00:00|2024-03-05    |80    |
|104     |Chen    |2024-03-10|2024-03-10 07:15:30|NULL          |310   |
|105     |Ben     |2024-03-28|2024-03-28 18:45:00|2024-04-02    |95    |
+--------+--------+----------+-------------------+--------------+------+

2. DATE vs TIMESTAMP

Spark has two main types for time:

TypeHoldsLiteralExample value
DATEA calendar dayDATE'2024-01-15'2024-01-15
TIMESTAMPA day and a time, to the microsecondTIMESTAMP'2024-01-15 09:30:00'2024-01-15 09:30:00

Use DATE when the time of day does not matter (birthdays, order dates). Use TIMESTAMP for events where the time matters (logins, clicks).

typeof() tells you the type of any expression, which is handy when a function does not behave as you expect:

SELECT typeof(DATE'2024-01-15')                   AS date_type,
       typeof(TIMESTAMP'2024-01-15 09:30:00')     AS ts_type,
       typeof('2024-01-15')                       AS text_type,
       cast(TIMESTAMP'2024-01-15 09:30:00' AS DATE) AS ts_to_date,
       cast(DATE'2024-01-15' AS TIMESTAMP)        AS date_to_ts
+---------+---------+---------+----------+-------------------+
|date_type|ts_type  |text_type|ts_to_date|date_to_ts         |
+---------+---------+---------+----------+-------------------+
|date     |timestamp|string   |2024-01-15|2024-01-15 00:00:00|
+---------+---------+---------+----------+-------------------+

Casting a timestamp to a date drops the time. Casting a date to a timestamp sets the time to midnight.


3. Parsing Text into Dates: to_date and to_timestamp

Dates often arrive as text, especially from CSV files. to_date(text, pattern) and to_timestamp(text, pattern) convert them. Without a pattern, they expect the standard yyyy-MM-dd and yyyy-MM-dd HH:mm:ss formats.

SELECT to_date('2024-01-15')                             AS iso_date,
       to_date('15/01/2024', 'dd/MM/yyyy')               AS indian_style,
       to_date('01-15-2024', 'MM-dd-yyyy')               AS us_style,
       to_date('15 Jan 2024', 'dd MMM yyyy')             AS month_name,
       to_timestamp('2024-01-15 09:30', 'yyyy-MM-dd HH:mm') AS ts
+----------+------------+----------+----------+-------------------+
|iso_date  |indian_style|us_style  |month_name|ts                 |
+----------+------------+----------+----------+-------------------+
|2024-01-15|2024-01-15  |2024-01-15|2024-01-15|2024-01-15 09:30:00|
+----------+------------+----------+----------+-------------------+

The pattern describes how the text is laid out. The most common letters:

LetterMeaningExample
yyyy4-digit year2024
MMMonth number, 2 digits01
MMM / MMMMShort / full month nameJan / January
ddDay of month15
HHHour, 0-2309
mmMinute30
ssSecond00
E / EEEEShort / full day nameMon / Monday

Common mistake: MM is month and mm is minute. Writing yyyy-mm-dd is one of the most common date bugs in Spark. Letters are case-sensitive.

What happens with text that is not a valid date? In Spark 3.5 with default settings, you get NULL instead of an error:

SELECT to_date('2024-02-30')               AS impossible_day,
       to_date('15/01/2024')               AS wrong_format,
       to_date('hello')                    AS not_a_date,
       to_date('2024-02-29')               AS leap_day
+--------------+------------+----------+----------+
|impossible_day|wrong_format|not_a_date|leap_day  |
+--------------+------------+----------+----------+
|NULL          |NULL        |NULL      |2024-02-29|
+--------------+------------+----------+----------+

February 30 does not exist, and 15/01/2024 does not match the default pattern, so both become NULL. This is convenient but dangerous: bad rows disappear quietly. After parsing, count the NULL results to catch them. (With ANSI mode on, the default on Databricks SQL warehouses and in Spark 4, invalid input raises an error instead.)


4. Formatting Dates as Text: date_format

date_format(date_or_ts, pattern) does the reverse: it turns a date into text, using the same pattern letters.

SELECT order_id,
       date_format(order_date, 'dd/MM/yyyy')       AS indian_style,
       date_format(order_date, 'MMM d, yyyy')      AS readable,
       date_format(order_date, 'EEEE')             AS day_name,
       date_format(order_ts, 'yyyy-MM')            AS year_month,
       date_format(order_ts, 'hh:mm a')            AS time_12h
FROM orders
ORDER BY order_id
+--------+------------+------------+---------+----------+--------+
|order_id|indian_style|readable    |day_name |year_month|time_12h|
+--------+------------+------------+---------+----------+--------+
|101     |15/01/2024  |Jan 15, 2024|Monday   |2024-01   |09:30 AM|
|102     |31/01/2024  |Jan 31, 2024|Wednesday|2024-01   |10:05 PM|
|103     |29/02/2024  |Feb 29, 2024|Thursday |2024-02   |02:00 PM|
|104     |10/03/2024  |Mar 10, 2024|Sunday   |2024-03   |07:15 AM|
|105     |28/03/2024  |Mar 28, 2024|Thursday |2024-03   |06:45 PM|
+--------+------------+------------+---------+----------+--------+

date_format always returns a string. Use it for display or for building labels like 2024-01, but keep the original date column for sorting and calculations.


5. Extracting Parts of a Date

These functions return a number for one part of a date or timestamp:

SELECT order_id,
       order_ts,
       year(order_ts)       AS yr,
       quarter(order_ts)    AS qtr,
       month(order_ts)      AS mon,
       day(order_ts)        AS dy,
       dayofweek(order_ts)  AS dow,
       weekofyear(order_ts) AS wk,
       hour(order_ts)       AS hr,
       minute(order_ts)     AS mins
FROM orders
ORDER BY order_id
+--------+-------------------+----+---+---+---+---+---+---+----+
|order_id|order_ts           |yr  |qtr|mon|dy |dow|wk |hr |mins|
+--------+-------------------+----+---+---+---+---+---+---+----+
|101     |2024-01-15 09:30:00|2024|1  |1  |15 |2  |3  |9  |30  |
|102     |2024-01-31 22:05:45|2024|1  |1  |31 |4  |5  |22 |5   |
|103     |2024-02-29 14:00:00|2024|1  |2  |29 |5  |9  |14 |0   |
|104     |2024-03-10 07:15:30|2024|1  |3  |10 |1  |10 |7  |15  |
|105     |2024-03-28 18:45:00|2024|1  |3  |28 |5  |13 |18 |45  |
+--------+-------------------+----+---+---+---+---+---+---+----+

Common mistake: dayofweek counts from Sunday = 1 to Saturday = 7. 2024-01-15 was a Monday, so it returns 2. If you need Monday = 1, use weekday(d) + 1 (weekday returns Monday = 0).

weekofyear follows the ISO standard: weeks start on Monday, and week 1 is the week that contains the first Thursday of the year.

The SQL-standard EXTRACT syntax does the same thing:

SELECT EXTRACT(YEAR FROM order_date)  AS yr,
       EXTRACT(MONTH FROM order_date) AS mon,
       EXTRACT(DAY FROM order_date)   AS dy
FROM orders
WHERE order_id = 103
+----+---+---+
|yr  |mon|dy |
+----+---+---+
|2024|2  |29 |
+----+---+---+

6. Adding and Subtracting Time

FunctionWhat it does
date_add(d, n)Add n days
date_sub(d, n)Subtract n days
add_months(d, n)Add n months (negative to go back)
ts + INTERVAL ...Add any amount of time to a timestamp
SELECT order_id,
       order_date,
       date_add(order_date, 7)              AS plus_week,
       date_sub(order_date, 1)              AS day_before,
       add_months(order_date, 1)            AS plus_month,
       order_ts + INTERVAL 3 HOURS          AS ts_plus_3h
FROM orders
ORDER BY order_id
+--------+----------+----------+----------+----------+-------------------+
|order_id|order_date|plus_week |day_before|plus_month|ts_plus_3h         |
+--------+----------+----------+----------+----------+-------------------+
|101     |2024-01-15|2024-01-22|2024-01-14|2024-02-15|2024-01-15 12:30:00|
|102     |2024-01-31|2024-02-07|2024-01-30|2024-02-29|2024-02-01 01:05:45|
|103     |2024-02-29|2024-03-07|2024-02-28|2024-03-29|2024-02-29 17:00:00|
|104     |2024-03-10|2024-03-17|2024-03-09|2024-04-10|2024-03-10 10:15:30|
|105     |2024-03-28|2024-04-04|2024-03-27|2024-04-28|2024-03-28 21:45:00|
+--------+----------+----------+----------+----------+-------------------+

Look at add_months for orders 102 and 103. January 31 plus one month would be "February 31", which does not exist, so Spark returns the last day of February (the 29th in 2024). Starting from February 29, the 29th of March is a real date, so you get March 29, not March 31.

Order 102 also shows that adding hours can roll the timestamp over into the next day.


7. Measuring Gaps: datediff and months_between

datediff(end, start) returns the number of days from start to end. The end date comes first, which trips up many people.

SELECT order_id,
       order_date,
       delivered_date,
       datediff(delivered_date, order_date)              AS days_to_deliver,
       datediff(order_date, delivered_date)              AS reversed,
       round(months_between(delivered_date, order_date), 2) AS months
FROM orders
ORDER BY order_id
+--------+----------+--------------+---------------+--------+------+
|order_id|order_date|delivered_date|days_to_deliver|reversed|months|
+--------+----------+--------------+---------------+--------+------+
|101     |2024-01-15|2024-01-18    |3              |-3      |0.1   |
|102     |2024-01-31|2024-02-03    |3              |-3      |0.1   |
|103     |2024-02-29|2024-03-05    |5              |-5      |0.23  |
|104     |2024-03-10|NULL          |NULL           |NULL    |NULL  |
|105     |2024-03-28|2024-04-02    |5              |-5      |0.16  |
+--------+----------+--------------+---------------+--------+------+
  • Swapping the arguments flips the sign.
  • Order 104 has no delivery date, so every calculation on it returns NULL.
  • months_between returns a fraction, based on a 31-day month.

For the difference between two timestamps in seconds, subtract their Unix times (section 9):

SELECT unix_timestamp(TIMESTAMP'2024-01-15 11:00:00')
     - unix_timestamp(TIMESTAMP'2024-01-15 09:30:00') AS seconds_apart
+-------------+
|seconds_apart|
+-------------+
|5400         |
+-------------+

8. Rounding Dates: date_trunc, trunc, last_day, next_day

Truncating a date "rounds it down" to the start of a period. This is the key to monthly and weekly reports.

SELECT order_id,
       order_ts,
       date_trunc('MONTH', order_ts) AS month_start_ts,
       trunc(order_date, 'MM')       AS month_start,
       date_trunc('WEEK', order_ts)  AS week_start_ts,
       last_day(order_date)          AS month_end,
       next_day(order_date, 'MON')   AS next_monday
FROM orders
ORDER BY order_id
+--------+-------------------+-------------------+-----------+-------------------+----------+-----------+
|order_id|order_ts           |month_start_ts     |month_start|week_start_ts      |month_end |next_monday|
+--------+-------------------+-------------------+-----------+-------------------+----------+-----------+
|101     |2024-01-15 09:30:00|2024-01-01 00:00:00|2024-01-01 |2024-01-15 00:00:00|2024-01-31|2024-01-22 |
|102     |2024-01-31 22:05:45|2024-01-01 00:00:00|2024-01-01 |2024-01-29 00:00:00|2024-01-31|2024-02-05 |
|103     |2024-02-29 14:00:00|2024-02-01 00:00:00|2024-02-01 |2024-02-26 00:00:00|2024-02-29|2024-03-04 |
|104     |2024-03-10 07:15:30|2024-03-01 00:00:00|2024-03-01 |2024-03-04 00:00:00|2024-03-31|2024-03-11 |
|105     |2024-03-28 18:45:00|2024-03-01 00:00:00|2024-03-01 |2024-03-25 00:00:00|2024-03-31|2024-04-01 |
+--------+-------------------+-------------------+-----------+-------------------+----------+-----------+

Note the argument order and the return types, because they differ:

FunctionUnit goesReturns
date_trunc(unit, ts)FirstTIMESTAMP
trunc(date, unit)SecondDATE

Weeks start on Monday, so date_trunc('WEEK', ...) returns the Monday of that week. next_day returns the next matching weekday after the date, never the date itself: order 101 was already on a Monday (2024-01-15), so its next_monday is a week later.


9. Unix Time: unix_timestamp and from_unixtime

Many systems store time as a Unix timestamp: the number of seconds since 1970-01-01 00:00:00 UTC.

SELECT unix_timestamp(TIMESTAMP'2024-01-15 09:30:00')      AS to_unix,
       from_unixtime(1705311000)                          AS from_unix,
       from_unixtime(1705311000, 'yyyy-MM-dd')            AS from_unix_date,
       timestamp_seconds(1705311000)                      AS as_timestamp,
       unix_timestamp('15/01/2024', 'dd/MM/yyyy')         AS from_text
+----------+-------------------+--------------+-------------------+----------+
|to_unix   |from_unix          |from_unix_date|as_timestamp       |from_text |
+----------+-------------------+--------------+-------------------+----------+
|1705311000|2024-01-15 09:30:00|2024-01-15    |2024-01-15 09:30:00|1705276800|
+----------+-------------------+--------------+-------------------+----------+

from_unixtime returns a string, while timestamp_seconds returns a real TIMESTAMP. Prefer timestamp_seconds when you plan to keep calculating.


10. Grouping by Month

To build a monthly report, truncate each date to its month and group on that:

SELECT trunc(order_date, 'MM')          AS month,
       date_format(order_date, 'MMM yyyy') AS label,
       COUNT(*)                         AS orders,
       SUM(amount)                      AS revenue
FROM orders
GROUP BY trunc(order_date, 'MM'), date_format(order_date, 'MMM yyyy')
ORDER BY month
+----------+--------+------+-------+
|month     |label   |orders|revenue|
+----------+--------+------+-------+
|2024-01-01|Jan 2024|2     |370    |
|2024-02-01|Feb 2024|1     |80     |
|2024-03-01|Mar 2024|2     |405    |
+----------+--------+------+-------+

Grouping on trunc(order_date, 'MM') keeps a real date, so ORDER BY month sorts in calendar order. If you sorted by the text label instead, "Feb 2024" would come before "Jan 2024".

Common mistake: Grouping by month(order_date) alone. It returns 1 to 12 with no year, so January 2024 and January 2025 land in the same group. Group by year and month together, or by the truncated date.


11. Current Date and Time Zones

current_date() and current_timestamp() return the date and time when the query starts, so their results change every time you run them:

-- Syntax
SELECT current_date()      AS today,
       current_timestamp() AS now,
       datediff(current_date(), order_date) AS days_ago
FROM orders

Timestamps are stored in UTC internally, and Spark shows them in the session time zone. You can check or change it:

-- Syntax
SET spark.sql.session.timeZone = Asia/Kolkata;
SELECT current_timestamp();

In PySpark you can also set it with spark.conf.set("spark.sql.session.timeZone", "UTC"). Set it once at the start of a job, so every timestamp is read and shown the same way.


12. Quick Reference

TaskFunction
Text to date / timestampto_date(s, fmt), to_timestamp(s, fmt)
Date to textdate_format(d, fmt)
Parts of a dateyear, quarter, month, day, dayofweek, weekofyear, hour, EXTRACT
Add / subtractdate_add, date_sub, add_months, + INTERVAL
Differencedatediff(end, start), months_between(end, start)
Start of perioddate_trunc(unit, ts), trunc(d, unit)
End of month / next weekdaylast_day(d), next_day(d, 'MON')
Unix secondsunix_timestamp, from_unixtime, timestamp_seconds

13. Try It in the Online Compiler

Copy this into the PySpark Online Compiler:

from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("Spark SQL Date Functions").getOrCreate()
spark.conf.set("spark.sql.session.timeZone", "UTC")

spark.sql("""
CREATE OR REPLACE TEMP VIEW orders AS
SELECT * FROM VALUES
  (101, 'Asha', DATE'2024-01-15', TIMESTAMP'2024-01-15 09:30:00', DATE'2024-01-18', 250),
  (102, 'Ben',  DATE'2024-01-31', TIMESTAMP'2024-01-31 22:05:45', DATE'2024-02-03', 120),
  (103, 'Asha', DATE'2024-02-29', TIMESTAMP'2024-02-29 14:00:00', DATE'2024-03-05', 80),
  (104, 'Chen', DATE'2024-03-10', TIMESTAMP'2024-03-10 07:15:30', NULL,             310),
  (105, 'Ben',  DATE'2024-03-28', TIMESTAMP'2024-03-28 18:45:00', DATE'2024-04-02', 95)
AS orders(order_id, customer, order_date, order_ts, delivered_date, amount)
""")

spark.sql("""
SELECT order_id,
       datediff(delivered_date, order_date) AS days_to_deliver,
       add_months(order_date, 1)            AS plus_month,
       date_format(order_date, 'EEEE')      AS day_name
FROM orders
ORDER BY order_id
""").show(truncate=False)

spark.sql("""
SELECT trunc(order_date, 'MM') AS month, COUNT(*) AS orders, SUM(amount) AS revenue
FROM orders
GROUP BY trunc(order_date, 'MM')
ORDER BY month
""").show(truncate=False)

Summary

  • DATE holds a day; TIMESTAMP holds a day and a time. Write literals as DATE'2024-01-15' and TIMESTAMP'2024-01-15 09:30:00'.
  • to_date and to_timestamp parse text with a pattern; date_format turns dates back into text. MM is month, mm is minute.
  • With default settings in Spark 3.5, text that is not a valid date becomes NULL silently, so check for NULL after parsing.
  • datediff(end, start) puts the end date first. add_months snaps to the last day of the month when needed.
  • Use trunc(d, 'MM') or date_trunc('MONTH', ts) to group by month, and always keep the year in the group.
  • Set spark.sql.session.timeZone so timestamps are shown consistently.

Next, you will learn window functions, which let you rank rows and compute running totals without collapsing them into groups.