22. Month Start, Month End and Due Dates
Difficulty: Medium · Topics: Dates, Filtering & Selection
For each invoice in invoices (issue_date as YYYY-MM-DD), compute:
month_start: first day of the issue month,month_end: last day of the issue month,due_date: one calendar month after the issue date (if that day doesn't exist, the last day of that month).
Return invoice_id, issue_date, month_start, month_end, due_date.
Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
invoices
| invoice_id | issue_date |
|---|---|
| 1 | 2024-01-15 |
| 2 | 2024-01-31 |
| 3 | 2023-02-28 |
Expected output
| invoice_id | issue_date | month_start | month_end | due_date |
|---|---|---|---|---|
| 1 | 2024-01-15 | 2024-01-01 | 2024-01-31 | 2024-02-15 |
| 2 | 2024-01-31 | 2024-01-01 | 2024-01-31 | 2024-02-29 |
| 3 | 2023-02-28 | 2023-02-01 | 2023-02-28 | 2023-03-28 |
Hints
Hint 1
F.trunc("issue_date", "month") gives the first day of the month.Hint 2
F.last_day gives the last day, including leap years.Hint 3
F.add_months(col, 1) clamps to the month end (Jan 31 + 1 month = Feb 29 in 2024).Learn the concepts
- trunc / add_months · 4 min read. Truncate dates to the month or year and shift them by whole months, including month-end rules.
- select · 6 min read. Choose, rename and compute columns, and why select beats a chain of withColumn calls.
PySpark functions you'll practise
- trunc
- last_day
- add_months
- select
Related problems
- Label Late Shipments · Easy · Dates, Null Handling, Conditional Logic
- Data Quality: Null Count per Column · Medium · Null Handling, Filtering & Selection
- Parse Application Log Lines · Medium · Strings, Filtering & Selection
- Parse UTM Parameters · Medium · Strings, Conditional Logic, Filtering & Selection
- Customers Without Orders · Medium · Joins, Filtering & Selection
Browse
Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings · Data Lake · Lakehouse · Streaming · Data Prep for AI · Spark Performance
Difficulty: Easy · Medium · Hard · Learn · All problems · dbt practice