Extracting year, month, day in Pandas - Time & Space Complexity
We want to know how the time to extract year, month, and day from dates changes as we have more data.
How does the work grow when the list of dates gets bigger?
Analyze the time complexity of the following code snippet.
import pandas as pd
dates = pd.Series(pd.date_range(start='2020-01-01', periods=1000))
years = dates.dt.year
months = dates.dt.month
days = dates.dt.day
This code creates 1000 dates and extracts the year, month, and day from each date.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Extracting year, month, and day from each date in the series.
- How many times: Once for each date in the list (n times).
As the number of dates grows, the work to extract parts grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 extractions |
| 100 | About 100 extractions |
| 1000 | About 1000 extractions |
Pattern observation: The work grows directly with the number of dates.
Time Complexity: O(n)
This means the time to extract year, month, and day grows linearly as the number of dates increases.
[X] Wrong: "Extracting year, month, and day is constant time no matter how many dates there are."
[OK] Correct: Each date needs to be processed separately, so more dates mean more work.
Understanding how operations grow with data size helps you explain your code choices clearly and confidently.
"What if we extracted only the year instead of year, month, and day? 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
The.dtaccessor allows extraction of date parts like year, month, and day from datetime columns.Step 2: Identify the function of
The.dt.year.dt.yearextracts the year component from each datetime value in the column.Final Answer:
Extracts the year part from each date in the column -> Option AQuick Check:
.dt.year= year extraction [OK]
- Confusing .dt.year with .dt.month or .dt.day
- Trying to use .year directly without .dt
- Not converting column to datetime before extraction
date_col?Solution
Step 1: Recall pandas datetime accessor usage
To extract parts like month, you must use the.dtaccessor on a datetime column.Step 2: Identify correct syntax for month extraction
The correct syntax isdate_col.dt.month. Other options either miss.dtor use invalid methods.Final Answer:
date_col.dt.month -> Option AQuick Check:
Use .dt before date parts [OK]
- Using .month directly without .dt
- Trying to access month as a dictionary key
- Using non-existent methods like get_month()
import pandas as pd
df = pd.DataFrame({
'date': pd.to_datetime(['2023-01-15', '2022-12-31', '2024-07-04'])
})
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['day'] = df['date'].dt.day
df[['year', 'month', 'day']].values.tolist()Solution
Step 1: Convert strings to datetime
Thepd.to_datetimeconverts string dates to datetime objects correctly.Step 2: Extract year, month, day
Using.dt.year,.dt.month, and.dt.dayextracts integer parts of the date.Final Answer:
[[2023, 1, 15], [2022, 12, 31], [2024, 7, 4]] -> Option CQuick Check:
Extracted parts are integers, not strings [OK]
- Expecting strings instead of integers
- Mixing order of day, month, year
- Forgetting to convert to datetime first
df['year'] = df['date'].yearAssuming
df['date'] is a datetime column.Solution
Step 1: Understand pandas datetime access
Datetime columns require the.dtaccessor to extract parts like year.Step 2: Identify missing .dt accessor
The code misses.dt, sodf['date'].yearwill raise an error or not work as expected.Final Answer:
It should bedf['date'].dt.yearto access year -> Option DQuick Check:
Use .dt before year/month/day [OK]
- Omitting .dt accessor
- Trying to call year() as a method
- Converting datetime to string unnecessarily
df with a column 'timestamp' containing mixed string dates and some missing values (NaN). You want to create three new columns: 'year', 'month', and 'day'. Which approach correctly handles conversion and extraction without errors?Solution
Step 1: Convert mixed strings and NaN to datetime safely
Usingpd.to_datetime(..., errors='coerce')converts valid strings to datetime and invalid/missing to NaT without error.Step 2: Extract year, month, day using .dt accessor
After conversion, use.dt.year,.dt.month, and.dt.dayto get parts safely, even with NaT values.Final Answer:
df['timestamp'] = pd.to_datetime(df['timestamp'], errors='coerce'); df['year'] = df['timestamp'].dt.year; df['month'] = df['timestamp'].dt.month; df['day'] = df['timestamp'].dt.day -> Option BQuick Check:
Convert with errors='coerce' then extract parts [OK]
- Not converting strings to datetime first
- Extracting parts from string columns directly
- Ignoring missing values causing errors
Ready to prove it?
Pass the test and this pattern moves unknown
