47. 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).PySpark functions you'll practise
- trunc
- last_day
- add_months
- select
Related problems
- Monthly Retention by Cohort · Hard · Joins
- Three-Day Login Streak · Hard · Window Functions
- Trailing 3 Calendar Days (Range Frame) · Hard · Window Functions
- Sessionize a Clickstream · Hard · Window Functions
- Fill Missing Dates (Calendar Spine) · Hard · Joins
Browse
Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings
Difficulty: Easy · Medium · Hard · PySpark interview roadmap · All problems