0
0
Pandasdata~20 mins

Extracting year, month, day in Pandas - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Datetime Extraction 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
What is the output of this code snippet that extracts the year from a datetime column in a pandas DataFrame?
Pandas
import pandas as pd

df = pd.DataFrame({'date': pd.to_datetime(['2023-01-15', '2022-12-31', '2024-06-01'])})
df['year'] = df['date'].dt.year
print(df['year'].tolist())
A[2023, 2022, 2024]
B[15, 31, 1]
C[1, 12, 6]
D[2023-01-15, 2022-12-31, 2024-06-01]
Attempts:
2 left
💡 Hint
Use the .dt accessor to get the year from datetime values.
Predict Output
intermediate
2:00remaining
Extract month from a pandas datetime column
What will be printed by this code that extracts the month from a pandas datetime column?
Pandas
import pandas as pd

df = pd.DataFrame({'date': pd.to_datetime(['2023-01-15', '2022-12-31', '2024-06-01'])})
df['month'] = df['date'].dt.month
print(df['month'].tolist())
A[15, 31, 1]
B[2023-01-15, 2022-12-31, 2024-06-01]
C[2023, 2022, 2024]
D[1, 12, 6]
Attempts:
2 left
💡 Hint
The .dt.month extracts the month number from datetime values.
Predict Output
advanced
2:00remaining
Extract day from a pandas datetime column
What is the output of this code that extracts the day from a datetime column in pandas?
Pandas
import pandas as pd

df = pd.DataFrame({'date': pd.to_datetime(['2023-01-15', '2022-12-31', '2024-06-01'])})
df['day'] = df['date'].dt.day
print(df['day'].tolist())
A[2023-01-15, 2022-12-31, 2024-06-01]
B[15, 31, 1]
C[1, 12, 6]
D[2023, 2022, 2024]
Attempts:
2 left
💡 Hint
Use .dt.day to get the day number from datetime values.
data_output
advanced
2:00remaining
Count unique years in a datetime column
Given a pandas DataFrame with a datetime column, how many unique years are in the 'date' column after extracting the year?
Pandas
import pandas as pd

df = pd.DataFrame({'date': pd.to_datetime(['2023-01-15', '2022-12-31', '2024-06-01', '2023-07-20'])})
df['year'] = df['date'].dt.year
unique_years = df['year'].nunique()
print(unique_years)
A4
B1
C3
D2
Attempts:
2 left
💡 Hint
Use .nunique() to count unique values in a column.
🧠 Conceptual
expert
2:00remaining
Understanding datetime extraction behavior with missing values
What happens when you extract year, month, or day from a pandas datetime column that contains missing values (NaT)?
Pandas
import pandas as pd
import numpy as np

df = pd.DataFrame({'date': pd.to_datetime(['2023-01-15', None, '2024-06-01'])})
df['year'] = df['date'].dt.year
print(df['year'].tolist())
A[2023, <NA>, 2024]
B[2023, None, 2024]
C[2023, NaT, 2024]
D[2023, nan, 2024]
Attempts:
2 left
💡 Hint
Missing datetime values become pandas in extracted integer columns.