Bird
Raised Fist0
Data Analysis Pythondata~20 mins

Extracting date components (year, month, day) in Data Analysis Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Date Component Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Extract year from a pandas datetime column
Given the DataFrame df with a datetime column date, what is the output of df['date'].dt.year?
Data Analysis Python
import pandas as pd

df = pd.DataFrame({'date': pd.to_datetime(['2023-01-15', '2022-12-31', '2024-06-01'])})
result = df['date'].dt.year
print(result.tolist())
A[1, 12, 6]
B[15, 31, 1]
C[2023-01-15, 2022-12-31, 2024-06-01]
D[2023, 2022, 2024]
Attempts:
2 left
💡 Hint
Use the dt accessor to get date parts from pandas datetime columns.
❓ data_output
intermediate
2:00remaining
Extract month and day from datetime
What is the output of extracting month and day from the datetime column df['date'] using df['date'].dt.month and df['date'].dt.day?
Data Analysis Python
import pandas as pd

df = pd.DataFrame({'date': pd.to_datetime(['2023-01-15', '2022-12-31', '2024-06-01'])})
months = df['date'].dt.month
days = df['date'].dt.day
print(months.tolist(), days.tolist())
A[1, 12, 6] [15, 31, 1]
B[15, 31, 1] [1, 12, 6]
C[2023, 2022, 2024] [15, 31, 1]
D[1, 12, 6] [2023, 2022, 2024]
Attempts:
2 left
💡 Hint
Month and day are separate attributes accessed via dt.month and dt.day.
🔧 Debug
advanced
2:00remaining
Identify the error when extracting date components
What error will this code raise?
import pandas as pd

df = pd.DataFrame({'date': ['2023-01-15', '2022-12-31', '2024-06-01']})
years = df['date'].dt.year
print(years.tolist())
AAttributeError: Can only use .dt accessor with datetimelike values
BKeyError: 'year'
CTypeError: 'list' object is not callable
DNo error, prints [2023, 2022, 2024]
Attempts:
2 left
💡 Hint
Check the data type of the 'date' column before using .dt.
🚀 Application
advanced
2:30remaining
Create new columns for year, month, and day
Given a DataFrame df with a datetime column date, which code correctly adds three new columns year, month, and day with the respective date parts?
Adf[['year', 'month', 'day']] = df['date'].dt.year, df['date'].dt.month, df['date'].dt.day
Bdf['year'], df['month'], df['day'] = df['date'].dt.year, df['date'].dt.month, df['date'].dt.day
C
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['day'] = df['date'].dt.day
D
df['year'] = df['date'].year
df['month'] = df['date'].month
df['day'] = df['date'].day
Attempts:
2 left
💡 Hint
Use the dt accessor and assign each part to a separate column.
🧠 Conceptual
expert
2:30remaining
Understanding datetime component extraction behavior
If a pandas Series contains some missing datetime values (NaT), what will be the output of extracting the year component using series.dt.year?
AA Series of strings with years and 'NaT' for missing values
BA float Series with years and NaN for missing values
CAn integer Series with years and 0 for missing values
DRaises an error because of missing values
Attempts:
2 left
💡 Hint
Consider how pandas handles missing datetime values in numeric extraction.

Practice

(1/5)
1. What does the dt.year attribute do when applied to a pandas datetime column?
easy
A. Converts the dates to string format
B. Extracts the month part from each date in the column
C. Extracts the day part from each date in the column
D. Extracts the year part from each date in the column

Solution

  1. Step 1: Understand pandas datetime attributes

    The dt accessor allows extraction of date parts like year, month, day from datetime columns.
  2. Step 2: Identify what dt.year extracts

    dt.year specifically extracts the year component from each datetime value.
  3. Final Answer:

    Extracts the year part from each date in the column -> Option D
  4. Quick Check:

    dt.year = year extraction [OK]
Hint: Remember: dt.year extracts year, dt.month extracts month [OK]
Common Mistakes:
  • Confusing dt.year with dt.month or dt.day
  • Thinking dt.year converts to string
  • Using dt.year on non-datetime columns
2. Which of the following is the correct syntax to extract the month from a pandas datetime column named date_col?
easy
A. date_col.dt.month
B. date_col.month()
C. date_col['month']
D. month(date_col)

Solution

  1. Step 1: Recall pandas datetime accessor usage

    To extract date parts, use the dt accessor followed by the attribute without parentheses.
  2. Step 2: Identify correct syntax for month extraction

    The correct syntax is date_col.dt.month. Parentheses are not used because it's an attribute, not a method.
  3. Final Answer:

    date_col.dt.month -> Option A
  4. Quick Check:

    Use dt.month attribute, no parentheses [OK]
Hint: Use .dt.month without parentheses to get month [OK]
Common Mistakes:
  • Adding parentheses like date_col.month()
  • Trying to access month as a dictionary key
  • Using a function month() without import
3. Given the following code, what will be the output?
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())
medium
A. [1, 12, 7]
B. [15, 31, 4]
C. [2023, 2022, 2024]
D. ['Jan', 'Dec', 'Jul']

Solution

  1. Step 1: Understand the input dates and extraction

    The dates are '2023-01-15', '2022-12-31', and '2024-07-04'. Extracting dt.month gets the month numbers: 1, 12, and 7.
  2. Step 2: Convert the extracted months to list

    The tolist() method converts the pandas Series to a Python list: [1, 12, 7].
  3. Final Answer:

    [1, 12, 7] -> Option A
  4. Quick Check:

    Months extracted = [1, 12, 7] [OK]
Hint: dt.month returns month numbers as integers [OK]
Common Mistakes:
  • Confusing day with month values
  • Expecting month names instead of numbers
  • Using dt.day instead of dt.month
4. The following code throws an error. What is the main issue?
import pandas as pd

dates = pd.Series(['2023-01-15', '2022-12-31'])
years = dates.dt.year
print(years)
medium
A. print statement syntax is incorrect
B. dt.year is not a valid attribute
C. dates is not converted to datetime type before using dt accessor
D. dates should be a list, not a pandas Series

Solution

  1. Step 1: Check the data type of dates

    The dates Series contains strings, not datetime objects.
  2. Step 2: Understand dt accessor requirements

    The dt accessor works only on datetime dtype Series. Without conversion, it raises an error.
  3. Final Answer:

    dates is not converted to datetime type before using dt accessor -> Option C
  4. Quick Check:

    Convert strings to datetime before dt.year [OK]
Hint: Always convert to datetime before using dt attributes [OK]
Common Mistakes:
  • Forgetting pd.to_datetime conversion
  • Assuming dt.year works on string Series
  • Misreading error as syntax problem
5. You have a DataFrame 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?
hard
A. df['year'] = df['order_date'].year df['month'] = df['order_date'].month df['day'] = df['order_date'].day
B. df['year'] = df['order_date'].dt.year df['month'] = df['order_date'].dt.month df['day'] = df['order_date'].dt.day
C. 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)
D. df['year'] = df['order_date'].str.year df['month'] = df['order_date'].str.month df['day'] = df['order_date'].str.day

Solution

  1. Step 1: Confirm datetime column usage

    To extract date parts efficiently, use the dt accessor on the datetime column.
  2. 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 uses dt.year, dt.month, and dt.day correctly. 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 uses str accessor.
  3. Final Answer:

    df['year'] = df['order_date'].dt.year df['month'] = df['order_date'].dt.month df['day'] = df['order_date'].dt.day -> Option B
  4. Quick Check:

    Use .dt accessor for vectorized date extraction [OK]
Hint: Use .dt.year, .dt.month, .dt.day for fast extraction [OK]
Common Mistakes:
  • Accessing year/month/day directly on Series
  • Using .str accessor on datetime columns
  • Using apply unnecessarily slowing code
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard