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
On this page
Show code in
Every code block on the page follows this.
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
| Function | Input | Example result |
|---|---|---|
trunc(d, "month") | date | 2025-03-31 → 2025-03-01 |
trunc(d, "quarter") | date | 2025-05-20 → 2025-04-01 |
trunc(d, "year") | date | 2025-05-20 → 2025-01-01 |
date_trunc("hour", ts) | timestamp | 10:47:12 → 10:00:00 |
add_months(d, 1) | date | 2025-01-31 → 2025-02-28 |
last_day(d) | date | 2025-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.
Step by step: monthly revenue
Input
| order_date | amount |
|---|---|
| 2025-01-15 | 100 |
| 2025-01-31 | 40 |
| 2025-02-10 | 70 |
| 2025-03-30 | 90 |
| 2025-03-31 | 60 |
Output
| month | revenue |
|---|---|
| 2025-01-01 | 140 |
| 2025-02-01 | 70 |
| 2025-03-01 | 150 |
Truncating to the month gives every order in a month the same key, ready for groupBy.
Run the example
Input: orders
| order_id | order_date | amount |
|---|---|---|
| 1 | 2025-01-15 | 100 |
| 2 | 2025-01-31 | 40 |
| 3 | 2025-02-10 | 70 |
| 4 | 2025-03-30 | 90 |
| 5 | 2025-03-31 | 60 |
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)vsdate_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."
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?"
Scenario"Compare each month's revenue to the same month last year."
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."
date_trunc("month", ts), which returns a timestamp. Note the swapped argument order between the two.Check yourself
3 questionsWhat 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 readRegular 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
lag / leadPySpark functions · 6 min read
rangeBetweenPySpark functions · 4 min read
groupBy + agg
Previous: pivot
Primary sources: functions.trunc · functions.add_months · Datetime patterns