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 to Q1.
  • Months 04–06 (April–June) map to Q2.
  • Months 07–09 (July–September) map to Q3.
  • Months 10–12 (October–December) map to Q4.

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 (NULL in SQL), in which case the corresponding label must be None (NULL).
  • Output order in Python must match the input order of dates (including duplicates).

Step-by-step walkthrough

  1. Understand the goal and input shapes

    Every record encodes its calendar date as an 8-digit integer in YYYYMMDD layout. For instance, 20250218 stands for 2025-02-18 (February 18, 2025). Our goal is to transform each integer date into a quarter tag YYYY_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 of YYYYMMDD integers (plus None for missing entries) and returns 'YYYY_Qn' strings in the identical order.
    • SQL contract: select id, trans_dt, and quarter_label from transactions, yielding NULL whenever trans_dt is NULL.

    Notice right away that the day digits (DD) never change the quarter. February 29 (20240229) and March 31 (20240331) both fall in 2024_Q1. Only the 4-digit year and 2-digit month matter.

  2. Why integer division beats full calendar parsing here

    One valid approach turns each integer into a string ("20250218"), parses a datetime object via datetime.strptime, reads .year and .month, and looks up the quarter. That makes a great randomized test oracle because it also flags impossible calendar dates like 20250230.

    When inputs are guaranteed to be valid YYYYMMDD integers, 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.

  3. 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), leaving YYYY.
    • Dividing by 100 (10^2) drops the rightmost 2 digits (DD), leaving YYYYMM.
    • Taking % 100 of YYYYMM isolates its last 2 digits, giving MM.

    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_month explicitly makes operator order crystal clear at a glance.

  4. 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 + 1 directly fails on the third month of every quarter: March gives 3 // 3 + 1 = 2 (Q2 instead of Q1), and December gives 12 // 3 + 1 = 5 (Q5!). Integer division by 3 groups numbers starting at zero (0..2, 3..5, 6..8, 9..11), whereas calendar months are 1-indexed.

    Shift month down by 1 first, divide by 3, and add 1 back:

    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  4
    

    Every boundary (3 -> 4, 6 -> 7, 9 -> 10) now transitions on the exact right month.

  5. Write the SQL query

    In SQLite and PostgreSQL, / on two INTEGER operands performs integer division, % computes the remainder, and || concatenates text. Standard SQL NULL propagation also means that when trans_dt is NULL, the arithmetic and concatenation automatically evaluate to NULL with no extra CASE branch 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 CASE expression 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 (use DIV for integer division) and joins strings with CONCAT(...).

  6. Write the Python helper and trace Example 1

    Wrapping single-value conversion in quarter_label(date) keeps convert_dates_to_quarter_labels clean, and guarding if date is None: upfront mirrors SQL NULL behavior without raising TypeError.

    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'
    
  7. 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 in Q1).
  • 20240401: year = 2024, month = 4, quarter = (4 - 1) // 3 + 1 = 2 -> '2024_Q2' (April 1 enters Q2).
  • None: caught immediately by if date is None: -> None (matching SQL NULL).

Complexity

  • Time: O(n) across n entries. Python performs four constant-time integer operations and one short string format per element; SQL executes a single sequential scan over the n rows of transactions.
  • Space: O(n) to store the returned list of n labels, using O(1) auxiliary working variables (year, year_and_month, month, quarter) per element.

Edge cases

  • Quarter transition days (Example 2): 20240331 lands in 2024_Q1 while 20240401 lands in 2024_Q2; June 30 / July 1 and September 30 / October 1 flip cleanly for the same reason.
  • Year rollover: 20221231 outputs 2022_Q4 and 20230101 outputs 2023_Q1 directly from their top four digits.
  • Leap day: 20240229 extracts month = 2 and maps to 2024_Q1.
  • Missing (None / NULL) values (Example 3): None returns None in Python and NULL yields NULL in SQL without dropping rows.
  • Empty input: [] returns [] (and an empty transactions table returns zero rows).
  • Corrupt upstream numbers: arithmetic alone will not flag invalid calendar dates such as 20250230 or 42; validate upstream when inputs are untrusted.

Common mistakes

  • Using month // 3 + 1 instead of (month - 1) // 3 + 1: forgets 1-based month numbering and shifts March, June, September, and December one quarter too high.
  • Reading date % 100 instead 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 + 1 produces floats like '2025_Q1.3333333333333333'; in MySQL, / yields decimals unless DIV is used.
  • Off-by-one string slicing: slicing str(date)[5:7] instead of [4:6] mixes month and day digits, and str(None) silently becomes "None" without an explicit None guard.
  • Filtering out NULL rows in SQL: adding WHERE trans_dt IS NOT NULL drops records instead of keeping one row per transaction with a NULL label.

Alternative approaches

  • Calendar parsing (datetime.strptime): parsed = datetime.strptime(str(date), "%Y%m%d") followed by (parsed.month - 1) // 3 + 1 runs slower due to string allocation and calendar checks, but automatically raises ValueError on bad dates.
  • Vectorized pandas column math: cast columns with missing dates to "Int64" — a nullable integer dtype (storing whole numbers alongside pd.NA without coercing values to float64) — 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] by month to 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). Shift month with modular arithmetic — quarter = ((month - start_month) % 12) // 3 + 1 — so start_month maps to 0 (Q1) and wraps December smoothly into January. Because fiscal years are typically named after the calendar year in which they close, add 1 to year whenever start_month > 1 and month >= 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 WITH at the top of a statement — and run SELECT 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 digit 1..4, lexicographic sorting (ORDER BY quarter_label) matches chronological order automatically, and an index on trans_dt still 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 20250230 into '2025_Q1' and 42 into '0_Q1', masking broken upstream ingestion. Validate each non-null value with datetime.strptime(str(date), "%Y%m%d") in Python (or join against a pre-populated dim_date calendar dimension table of valid YYYYMMDD keys in SQL), route malformed records to NULL or a quarantine table according to business rules, and emit a data-quality alert counter whenever invalid dates appear.

Follow-up questions

Similar questions

More Point72 interview questions

All 41 Point72 questions →