Skip to content
Silver 4 min read · Dates 3 practice problems ↓

trunc / add_months

Monthly reports, quarter-to-date numbers and "same month last year" comparisons all need dates rounded to a month or shifted by months. trunc, date_trunc and add_months do that. This lesson shows each one, their argument-order trap, and how they handle the end of a month.

Step 1 · PySpark functions · Silver · Reshape and refine, lesson 5 of 7

Read first: select · groupBy + agg (skip if you know them)

In plain words first

Filing receipts by month, you ignore the exact day: anything from March goes in the "March" folder, which is labelled with March 1st. That is truncating a date. Moving a reminder "one month later" from January 31st is the tricky part: there is no February 31st, so it lands on the last day of February.

What they do

FunctionInputExample result
trunc(d, "month")date2025-03-31 → 2025-03-01
trunc(d, "quarter")date2025-05-20 → 2025-04-01
trunc(d, "year")date2025-05-20 → 2025-01-01
date_trunc("hour", ts)timestamp10:47:12 → 10:00:00
add_months(d, 1)date2025-01-31 → 2025-02-28
last_day(d)date2025-02-10 → 2025-02-28

Note the argument order: trunc(column, unit) but date_trunc(unit, column). trunc returns a date and only knows date units; date_trunc returns a timestamp and also handles hours, minutes and weeks.

How add_months handles month ends

Adding a month to January 31 cannot give February 31. Spark returns the last day of the target month instead: February 28 (or 29 in a leap year). Going back is not symmetric: add_months("2025-02-28", 1) is March 28, not March 31.

Note: Spark 2 and Spark 3 differ here. Spark 2 kept "last day stays last day", so Feb 28 + 1 month gave Mar 31. Spark 3 adds the months and only clamps when the day does not exist.

Step by step: monthly revenue

Input

order_dateamount
2025-01-15100
2025-01-3140
2025-02-1070
2025-03-3090
2025-03-3160

Output

monthrevenue
2025-01-01140
2025-02-0170
2025-03-01150

Truncating to the month gives every order in a month the same key, ready for groupBy.

Run the example

PySparkSpark SQL

Input: orders

order_idorder_dateamount
12025-01-15100
22025-01-3140
32025-02-1070
42025-03-3090
52025-03-3160
from pyspark.sql import functions as F
result = (orders
    .withColumn("month", F.trunc("order_date", "month"))
    .groupBy("month").agg(F.sum("amount").alias("revenue"))
    .withColumn("next_month", F.add_months("month", 1))
    .orderBy("month"))
SELECT trunc(order_date, 'month')                AS month,
       SUM(amount)                                 AS revenue,
       add_months(trunc(order_date, 'month'), 1)   AS next_month
FROM orders
GROUP BY trunc(order_date, 'month')
ORDER BY month

Month over month

Three ways to compare each month with the one before it:

  • lag(revenue) over the months in order. Fast and short. But it compares with the previous row, so if March has no data, April is compared with February.
  • Join the monthly table to itself on a.month = add_months(b.month, 1). It always compares with the previous calendar month, even when a month is missing, and the condition says exactly which month is compared.
  • Build a calendar first with sequence(start, end, interval 1 month) and left joinleft join: A join that keeps every row of the left table, with nulls where the right side has no match. Learn more → the data to it. Use this when every month must appear in the output, including months with no data.

Parsing first

These functions need real dates. A string in ISO format (yyyy-MM-dd) is cast automatically; anything else must be parsed with F.to_date(col, "dd/MM/yyyy"). In Spark 3, an unparseable string returns nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more →; with ANSI mode in Spark 4.0, to_date raises an error unless you use try_to_date.

Common mistakes

  • Swapping the arguments of trunc and date_trunc — trunc(col, unit) vs date_trunc(unit, col). Swapped arguments return null or fail.
  • Grouping by month(date) alone — month() returns 1 to 12, so January 2024 and January 2025 merge. Truncate instead.
  • Using lag for month over month with gaps — If a month has no rows, lag compares with the month before it.

Key takeaways

  • trunc(date, unit) gives the start of the month, quarter or year.
  • date_trunc(unit, ts) does the same for timestamps, with finer units.
  • add_months clamps to the last valid day; it is not symmetric.
  • Group by the truncated date, not month(), to keep years apart.

Interview prep

THE QUESTION

"Compute each customer's revenue this month vs the previous month."

Truncate to the month, aggregate per customer and month, then either lag over months or self-join on add_months(prev.month, 1) = cur.month. Call out the gap problem with lag and the year-merging bug of grouping by month().

Avoid: grouping by month(date). It merges January 2024 and January 2025; truncate to the month instead.

Follow-ups · answer out loud, then open

Follow-up"What does add_months('2025-01-31', 1) return?"
2025-02-28. If the day does not exist in the target month, Spark uses the last day of that month.
Scenario"Compare each month's revenue to the same month last year."
Aggregate per month (trunc to month), then self-join on cur.month = add_months(prev.month, 12), or lag 12 over a complete calendar of months. The calendar matters: lag over months with gaps compares the wrong months.
Trap"trunc('ts', 'month') works on timestamps and returns a timestamp."
trunc returns a date. For timestamps, use date_trunc("month", ts), which returns a timestamp. Note the swapped argument order between the two.

Check yourself

3 questions

What is add_months('2025-01-31', 1)?

Show the answer

2025-02-28. February 31 does not exist, so Spark clamps to the last day of February.

Why is grouping by F.month("order_date") risky?

Show the answer

It returns 1 to 12, merging the same month of different years. month() drops the year. Truncate to the month to keep a full date key.

Which call is correct for a timestamp column ts?

Show the answer

F.date_trunc("hour", "ts"). date_trunc takes the unit first and supports hours. trunc takes the column first and only date units.

Practise this

Problems that use trunc / add_months, graded on hidden tests

Keep going

Up next · Reshape and refine · lesson 6 of 7 · 8 min read
Regular expressions from zero
What a regex is, the dozen symbols behind almost every pattern, and how to read and build one piece by piece.

Related lessons

Previous: pivot

Primary sources: functions.trunc · functions.add_months · Datetime patterns