Format Numeric Dates as Quarter Labels
Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen
Problem Statement
Accounting pipelines often store calendar dates as 8-digit integers in YYYYMMDD layout (4 digits for the year, 2 digits for the month 01–12, and 2 digits for the day 01–31). To group activity into standard three-month reporting periods, map each valid date to its calendar quarter tag "YYYY_Qn":
- Months
01–03(January–March) map toQ1. - Months
04–06(April–June) map toQ2. - Months
07–09(July–September) map toQ3. - Months
10–12(October–December) map toQ4.
Implement convert_dates_to_quarter_labels(dates) in Python so it returns one "YYYY_Qn" string per entry in dates while preserving input order; if an entry is None, put None in the corresponding output position.
(SQL companion schema: Given a table transactions(id INTEGER, trans_dt INTEGER), select id, trans_dt, and quarter_label with one output row per input record in any row order, returning NULL for quarter_label whenever trans_dt is NULL.)
def convert_dates_to_quarter_labels(dates: List[int]) -> List[str]:
Examples
Example 1
Python input: dates = [20250218, 20250529, 20250811, 20251124]
Python output: ["2025_Q1", "2025_Q2", "2025_Q3", "2025_Q4"]
SQL input (transactions): SQL output:
+-----+----------+ +-----+----------+---------------+
| id | trans_dt | | id | trans_dt | quarter_label |
+-----+----------+ +-----+----------+---------------+
| 101 | 20250218 | | 101 | 20250218 | 2025_Q1 |
| 102 | 20250529 | | 102 | 20250529 | 2025_Q2 |
| 103 | 20250811 | | 103 | 20250811 | 2025_Q3 |
| 104 | 20251124 | | 104 | 20251124 | 2025_Q4 |
+-----+----------+ +-----+----------+---------------+
Walk-through: Months 02, 05, 08, and 11 fall into Q1, Q2, Q3, and Q4 of 2025, respectively.
Example 2
Input: dates = [20240229, 20240331, 20240401, 20240930, 20241001]
Output: ["2024_Q1", "2024_Q1", "2024_Q2", "2024_Q3", "2024_Q4"]
Walk-through: Leap day (20240229) and March 31 (20240331) both stay in 2024_Q1, April 1 (20240401) enters 2024_Q2, and September 30 (20240930) / October 1 (20241001) straddle the Q3–Q4 boundary.
Example 3
Input: dates = [20221231, None, 20260704]
Output: ["2022_Q4", None, "2026_Q3"]
Walk-through: Missing entries (None in Python, NULL in SQL) pass through as None / NULL without dropping or reordering surrounding entries.
Constraints
0 <= len(dates) <= 10^5- Every non-null element is a valid calendar date encoded as an 8-digit integer
YYYYMMDD(10000101 <= date <= 99991231). - Elements may be
None(NULLin SQL), in which case the corresponding label must beNone(NULL). - Output order in Python must match the input order of
dates(including duplicates).
Step-by-step walkthrough
Understand the goal and input shapes
Every record encodes its calendar date as an 8-digit integer in
YYYYMMDDlayout. For instance,20250218stands for2025-02-18(February 18, 2025). Our goal is to transform each integer date into a quarter tagYYYY_Qn:Input table: transactions Desired output +-----+----------+ +-----+----------+---------------+ | id | trans_dt | | id | trans_dt | quarter_label | +-----+----------+ +-----+----------+---------------+ | 101 | 20250218 | Jan–Mar = Q1 -> | 101 | 20250218 | 2025_Q1 | | 102 | 20250529 | Apr–Jun = Q2 -> | 102 | 20250529 | 2025_Q2 | | 103 | 20250811 | Jul–Sep = Q3 -> | 103 | 20250811 | 2025_Q3 | | 104 | 20251124 | Oct–Dec = Q4 -> | 104 | 20251124 | 2025_Q4 | | 105 | NULL | missing -> | 105 | NULL | NULL | +-----+----------+ +-----+----------+---------------+- Python contract:
convert_dates_to_quarter_labels(dates)takes a list ofYYYYMMDDintegers (plusNonefor missing entries) and returns'YYYY_Qn'strings in the identical order. - SQL contract: select
id,trans_dt, andquarter_labelfromtransactions, yieldingNULLwhenevertrans_dtisNULL.
Notice right away that the day digits (
DD) never change the quarter. February 29 (20240229) and March 31 (20240331) both fall in2024_Q1. Only the 4-digit year and 2-digit month matter.- Python contract:
Why integer division beats full calendar parsing here
One valid approach turns each integer into a string (
"20250218"), parses adatetimeobject viadatetime.strptime, reads.yearand.month, and looks up the quarter. That makes a great randomized test oracle because it also flags impossible calendar dates like20250230.When inputs are guaranteed to be valid
YYYYMMDDintegers, however, string conversion and full calendar object construction do extra work. Because base-10 digits occupy fixed slots, integer division and remainder operations isolate the year and month in a couple of arithmetic instructions — and the exact same math works in both Python and SQL.Extract year and month with base-10 arithmetic
In base 10, integer division (
//in Python, dividing and discarding any fractional part) drops digits from the right end of a positive integer, while the modulo operator (%, returning the division remainder) keeps only the rightmost digits:- Dividing by
10,000(10^4) drops the rightmost 4 digits (MMDD), leavingYYYY. - Dividing by
100(10^2) drops the rightmost 2 digits (DD), leavingYYYYMM. - Taking
% 100ofYYYYMMisolates its last 2 digits, givingMM.
Let's trace
date = 20250218:date = 20250218 (YYYY MM DD) year = date // 10000 = 2025 (drops 0218) year_and_month = date // 100 = 202502 (drops 18) month = year_and_month % 100 = 2 (keeps 02 -> 2)Naming
year_and_monthexplicitly makes operator order crystal clear at a glance.- Dividing by
Map months 1–12 onto quarters 1–4 cleanly
We need four groups of three months:
{1,2,3} -> 1,{4,5,6} -> 2,{7,8,9} -> 3, and{10,11,12} -> 4.Writing
month // 3 + 1directly fails on the third month of every quarter: March gives3 // 3 + 1 = 2(Q2instead ofQ1), and December gives12 // 3 + 1 = 5(Q5!). Integer division by3groups numbers starting at zero (0..2,3..5,6..8,9..11), whereas calendar months are 1-indexed.Shift
monthdown by1first, divide by3, and add1back:month 1 2 3 | 4 5 6 | 7 8 9 | 10 11 12 month - 1 0 1 2 | 3 4 5 | 6 7 8 | 9 10 11 (month - 1) // 3 0 0 0 | 1 1 1 | 2 2 2 | 3 3 3 (month - 1) // 3 + 1 1 1 1 | 2 2 2 | 3 3 3 | 4 4 4Every boundary (
3 -> 4,6 -> 7,9 -> 10) now transitions on the exact right month.Write the SQL query
In SQLite and PostgreSQL,
/on twoINTEGERoperands performs integer division,%computes the remainder, and||concatenates text. Standard SQLNULLpropagation also means that whentrans_dtisNULL, the arithmetic and concatenation automatically evaluate toNULLwith no extraCASEbranch required:SELECT id, trans_dt, -- Peel off YYYY, attach '_Q', and map MM (1..12) to quarter (1..4). -- When trans_dt is NULL, SQL NULL propagation makes the whole expression NULL. CAST(trans_dt / 10000 AS TEXT) || '_Q' || CAST((((trans_dt / 100) % 100 - 1) / 3 + 1) AS TEXT) AS quarter_label FROM transactions;If an explicit
CASEexpression reads better for your team, spell out the four ranges:SELECT id, trans_dt, -- Extract the 4-digit year and pair it with an explicit month-to-quarter CASE table. CAST(trans_dt / 10000 AS TEXT) || '_Q' || CASE WHEN (trans_dt / 100) % 100 BETWEEN 1 AND 3 THEN '1' WHEN (trans_dt / 100) % 100 BETWEEN 4 AND 6 THEN '2' WHEN (trans_dt / 100) % 100 BETWEEN 7 AND 9 THEN '3' WHEN (trans_dt / 100) % 100 BETWEEN 10 AND 12 THEN '4' END AS quarter_label FROM transactions;Dialect note: MySQL treats
/as floating-point division (useDIVfor integer division) and joins strings withCONCAT(...).Write the Python helper and trace Example 1
Wrapping single-value conversion in
quarter_label(date)keepsconvert_dates_to_quarter_labelsclean, and guardingif date is None:upfront mirrors SQLNULLbehavior without raisingTypeError.def quarter_label(date: Optional[int]) -> Optional[str]: """Convert an 8-digit YYYYMMDD integer (e.g. 20250218) into 'YYYY_Qn'.""" # Mirror SQL NULL propagation: a missing date produces a missing label. if date is None: return None # Drop the last 4 digits (MMDD) to isolate the 4-digit year, e.g. 20250218 -> 2025. year = date // 10000 # Drop the last 2 digits (DD) to get YYYYMM, then keep the last 2 digits for MM (1..12). year_and_month = date // 100 month = year_and_month % 100 # Shift 1..12 down to 0..11 before dividing by 3 so March (3 -> 2) stays in Q1 # instead of spilling into Q2, then add 1 back to get quarter 1..4. quarter = (month - 1) // 3 + 1 return f"{year}_Q{quarter}"Tracing Example 1 (
[20250218, 20250529, 20250811, 20251124]):date year year_and_month month (month - 1) // 3 + 1 output label 20250218 2025 202502 2 (1 // 3) + 1 = 1 '2025_Q1' 20250529 2025 202505 5 (4 // 3) + 1 = 2 '2025_Q2' 20250811 2025 202508 8 (7 // 3) + 1 = 3 '2025_Q3' 20251124 2025 202511 11 (10 // 3) + 1 = 4 '2025_Q4'Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def quarter_label(date: Optional[int]) -> Optional[str]: """Convert an 8-digit YYYYMMDD integer (e.g. 20250218) into 'YYYY_Qn'.""" # Mirror SQL NULL propagation: a missing date produces a missing label. if date is None: return None # Drop the last 4 digits (MMDD) to isolate the 4-digit year, e.g. 20250218 -> 2025. year = date // 10000 # Drop the last 2 digits (DD) to get YYYYMM, then keep the last 2 digits for MM (1..12). year_and_month = date // 100 month = year_and_month % 100 # Shift 1..12 down to 0..11 before dividing by 3 so March (3 -> 2) stays in Q1 # instead of spilling into Q2, then add 1 back to get quarter 1..4. quarter = (month - 1) // 3 + 1 return f"{year}_Q{quarter}" def convert_dates_to_quarter_labels(dates: List[int]) -> List[str]: # labels: list of 'YYYY_Qn' strings (or None), one per input date in input order. labels: List[str] = [] for date in dates: labels.append(quarter_label(date)) return labels✅ Submit now — all tests should pass.
Intuition & how it works
Picture an 8-digit date integer like 20250218 as a fixed-width date stamp with three side-by-side compartments: four digits for the year (2025), two for the month (02), and two for the day (18). Just as dividing a cent amount by 100 drops the rightmost two digits, integer division (division that discards any fractional remainder) peels trailing digits off a base-10 integer without string allocation. Once the month (1 through 12) is isolated, grouping twelve months into four 3-month quarters works just like mapping twelve numbered rooms (1..12) onto four floors of three rooms apiece.
Parsing every integer as text via datetime.strptime works, yet spends CPU cycles validating day-of-month and leap-year rules that have zero effect on quarter labels. Meanwhile, writing month // 3 + 1 directly misclassifies the closing month of every quarter: March (3 // 3 + 1 = 2) spills into Q2 and December (12 // 3 + 1 = 5) invents Q5. Subtracting 1 first shifts 1..12 onto zero-based indices 0..11, where groups of three (0..2, 3..5, 6..8, 9..11) divide cleanly by 3.
Walk through four concrete inputs — [20250218, 20240331, 20240401, None]:
20250218:year = 20250218 // 10000 = 2025,month = (20250218 // 100) % 100 = 2(using%, the modulo operator that returns the division remainder),quarter = (2 - 1) // 3 + 1 = 1->'2025_Q1'.20240331:year = 2024,month = 3,quarter = (3 - 1) // 3 + 1 = 1->'2024_Q1'(March 31 stays inQ1).20240401:year = 2024,month = 4,quarter = (4 - 1) // 3 + 1 = 2->'2024_Q2'(April 1 entersQ2).None: caught immediately byif date is None:->None(matching SQLNULL).
Complexity
- Time:
O(n)acrossnentries. Python performs four constant-time integer operations and one short string format per element; SQL executes a single sequential scan over thenrows oftransactions. - Space:
O(n)to store the returned list ofnlabels, usingO(1)auxiliary working variables (year,year_and_month,month,quarter) per element.
Edge cases
- Quarter transition days (Example 2):
20240331lands in2024_Q1while20240401lands in2024_Q2; June 30 / July 1 and September 30 / October 1 flip cleanly for the same reason. - Year rollover:
20221231outputs2022_Q4and20230101outputs2023_Q1directly from their top four digits. - Leap day:
20240229extractsmonth = 2and maps to2024_Q1. - Missing (
None/NULL) values (Example 3):NonereturnsNonein Python andNULLyieldsNULLin SQL without dropping rows. - Empty input:
[]returns[](and an emptytransactionstable returns zero rows). - Corrupt upstream numbers: arithmetic alone will not flag invalid calendar dates such as
20250230or42; validate upstream when inputs are untrusted.
Common mistakes
- Using
month // 3 + 1instead of(month - 1) // 3 + 1: forgets 1-based month numbering and shifts March, June, September, and December one quarter too high. - Reading
date % 100instead of(date // 100) % 100: extracts the day (DD) instead of the month (MM). - Using float division
/instead of integer division//: in Python 3,(month - 1) / 3 + 1produces floats like'2025_Q1.3333333333333333'; in MySQL,/yields decimals unlessDIVis used. - Off-by-one string slicing: slicing
str(date)[5:7]instead of[4:6]mixes month and day digits, andstr(None)silently becomes"None"without an explicitNoneguard. - Filtering out
NULLrows in SQL: addingWHERE trans_dt IS NOT NULLdrops records instead of keeping one row per transaction with aNULLlabel.
Alternative approaches
- Calendar parsing (
datetime.strptime):parsed = datetime.strptime(str(date), "%Y%m%d")followed by(parsed.month - 1) // 3 + 1runs slower due to string allocation and calendar checks, but automatically raisesValueErroron bad dates. - Vectorized
pandascolumn math: cast columns with missing dates to"Int64"— a nullable integer dtype (storing whole numbers alongsidepd.NAwithout coercing values tofloat64) — and compute(s // 10000).astype(str) + "_Q" + (((s // 100) % 100 - 1) // 3 + 1).astype(str). - 13-slot lookup list: index
QUARTER_BY_MONTH = [None, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]bymonthto avoid division altogether.
Follow-up questions
- How would the formula change for a custom fiscal year that begins in a month other than January (for instance, October)? A fiscal year is an organization's 12-month accounting cycle, which can start on any month
start_month(such as October,start_month = 10). Shiftmonthwith modular arithmetic —quarter = ((month - start_month) % 12) // 3 + 1— sostart_monthmaps to0(Q1) and wraps December smoothly into January. Because fiscal years are typically named after the calendar year in which they close, add1toyearwheneverstart_month > 1andmonth >= start_month(turning October 2025 into'FY2026_Q1'). - Once quarter labels are computed in SQL, how would you roll up quarterly revenue totals in chronological order? Wrap the labeling query inside a CTE (Common Table Expression) — a named temporary view declared with
WITHat the top of a statement — and runSELECT quarter_label, SUM(amount) AS quarterly_revenue FROM labeled_tx GROUP BY quarter_label ORDER BY quarter_label;. Because'YYYY_Qn'places the 4-digit year ahead of the quarter digit1..4, lexicographic sorting (ORDER BY quarter_label) matches chronological order automatically, and an index ontrans_dtstill lets range filters (WHERE trans_dt BETWEEN 20250101 AND 20251231) prune partitions before grouping. - What safeguards would you add if upstream feeds occasionally deliver corrupt integers such as 20250230 or 42? Pure arithmetic silently converts
20250230into'2025_Q1'and42into'0_Q1', masking broken upstream ingestion. Validate each non-null value withdatetime.strptime(str(date), "%Y%m%d")in Python (or join against a pre-populateddim_datecalendar dimension table of validYYYYMMDDkeys in SQL), route malformed records toNULLor a quarantine table according to business rules, and emit a data-quality alert counter whenever invalid dates appear.
Follow-up questions
- How would the formula change for a custom fiscal year that begins in a month other than January (for instance, October)?
- Once quarter labels are computed in SQL, how would you roll up quarterly revenue totals in chronological order?
- What safeguards would you add if upstream feeds occasionally deliver corrupt integers such as 20250230 or 42?
Similar questions
- Summarize Final Auction Status and Duration
- Highest-Ranked Student in Each Department
- Calibrating Mean-Variance Risk Aversion in Practice
- Designing Convex Constraints for Statistical Arbitrage
- Classify Pairwise Circle Geometry
- Evaluating Imputation Methods in Linear Regression
More Point72 interview questions
- Classify Pairwise Circle Boundary Relationships Medium
- Presenting and Defending a Quantitative Alpha Signal Study Medium
- Optimal Bidding in Two-Bidder Second- and First-Price Auctions Hard Pro
- Principles and Core Families of Ensemble Models Medium Pro
- CART Mechanics, Pruning, and Scalable Tree Tuning Hard Pro
- K-th Absent Positive and Windowed Repeat Count Easy Pro
- Smallest Element in a Cyclically Shifted Array Medium Pro
- Minimal String After One Alphabetical Left-Shift Medium Pro
- Optimal Pairwise Weighings for Top Two Items Hard Pro
- Optimal Non-Overlapping Stock Trades Hard Pro