Extracting date components (year, month, day) in Data Analysis Python - Time & Space Complexity
We want to understand how the time to extract year, month, and day from dates changes as the data grows.
How does the work increase when we have more dates to process?
Analyze the time complexity of the following code snippet.
import pandas as pd
dates = pd.Series(pd.date_range('2023-01-01', periods=1000))
# Extract year, month, day
years = dates.dt.year
months = dates.dt.month
days = dates.dt.day
This code creates a list of dates and extracts the year, month, and day parts from each date.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Extracting each date component from every date in the list.
- How many times: Once for each date, repeated for year, month, and day extraction.
As the number of dates increases, the work to extract components grows directly with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 (10 dates x 3 components) |
| 100 | About 300 (100 dates x 3 components) |
| 1000 | About 3000 (1000 dates x 3 components) |
Pattern observation: The operations increase in a straight line as input size grows.
Time Complexity: O(n)
This means the time to extract date parts grows directly with the number of dates.
[X] Wrong: "Extracting year, month, and day all together takes three times longer than extracting just one."
[OK] Correct: Internally, these extractions often happen together efficiently, so the time grows mostly with the number of dates, not multiplied by the number of components.
Understanding how simple operations scale with data size helps you explain your code's efficiency clearly and confidently.
"What if we extracted date components from a filtered subset of dates instead of the whole list? How would the time complexity change?"
Practice
dt.year attribute do when applied to a pandas datetime column?Solution
Step 1: Understand pandas datetime attributes
Thedtaccessor allows extraction of date parts like year, month, day from datetime columns.Step 2: Identify what
dt.yearextractsdt.yearspecifically extracts the year component from each datetime value.Final Answer:
Extracts the year part from each date in the column -> Option DQuick Check:
dt.year= year extraction [OK]
- Confusing dt.year with dt.month or dt.day
- Thinking dt.year converts to string
- Using dt.year on non-datetime columns
date_col?Solution
Step 1: Recall pandas datetime accessor usage
To extract date parts, use thedtaccessor followed by the attribute without parentheses.Step 2: Identify correct syntax for month extraction
The correct syntax isdate_col.dt.month. Parentheses are not used because it's an attribute, not a method.Final Answer:
date_col.dt.month -> Option AQuick Check:
Usedt.monthattribute, no parentheses [OK]
- Adding parentheses like date_col.month()
- Trying to access month as a dictionary key
- Using a function month() without import
import pandas as pd dates = pd.Series(pd.to_datetime(['2023-01-15', '2022-12-31', '2024-07-04'])) months = dates.dt.month print(months.tolist())
Solution
Step 1: Understand the input dates and extraction
The dates are '2023-01-15', '2022-12-31', and '2024-07-04'. Extractingdt.monthgets the month numbers: 1, 12, and 7.Step 2: Convert the extracted months to list
Thetolist()method converts the pandas Series to a Python list: [1, 12, 7].Final Answer:
[1, 12, 7] -> Option AQuick Check:
Months extracted = [1, 12, 7] [OK]
- Confusing day with month values
- Expecting month names instead of numbers
- Using dt.day instead of dt.month
import pandas as pd dates = pd.Series(['2023-01-15', '2022-12-31']) years = dates.dt.year print(years)
Solution
Step 1: Check the data type of dates
ThedatesSeries contains strings, not datetime objects.Step 2: Understand dt accessor requirements
Thedtaccessor works only on datetime dtype Series. Without conversion, it raises an error.Final Answer:
dates is not converted to datetime type before using dt accessor -> Option CQuick Check:
Convert strings to datetime before dt.year [OK]
- Forgetting pd.to_datetime conversion
- Assuming dt.year works on string Series
- Misreading error as syntax problem
df with a datetime column 'order_date'. You want to add three new columns: 'year', 'month', and 'day' extracted from 'order_date'. Which code correctly does this?Solution
Step 1: Confirm datetime column usage
To extract date parts efficiently, use thedtaccessor on the datetime column.Step 2: Check each option's method
df['year'] = df['order_date'].dt.year df['month'] = df['order_date'].dt.month df['day'] = df['order_date'].dt.day usesdt.year,dt.month, anddt.daycorrectly. df['year'] = df['order_date'].year df['month'] = df['order_date'].month df['day'] = df['order_date'].day tries to access attributes directly on Series, which fails. df['year'] = df['order_date'].apply(lambda x: x.year) df['month'] = df['order_date'].apply(lambda x: x.month) df['day'] = df['order_date'].apply(lambda x: x.day) works but is slower due to apply. df['year'] = df['order_date'].str.year df['month'] = df['order_date'].str.month df['day'] = df['order_date'].str.day incorrectly usesstraccessor.Final Answer:
df['year'] = df['order_date'].dt.year df['month'] = df['order_date'].dt.month df['day'] = df['order_date'].dt.day -> Option BQuick Check:
Use .dt accessor for vectorized date extraction [OK]
- Accessing year/month/day directly on Series
- Using .str accessor on datetime columns
- Using apply unnecessarily slowing code
Ready to prove it?
Pass the test and this pattern moves unknown
