0
0
Pandasdata~20 mins

dt accessor for datetime properties in Pandas - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Datetime Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of extracting month using dt accessor
What is the output of this code snippet?
Pandas
import pandas as pd
s = pd.Series(pd.to_datetime(['2023-01-15', '2023-06-20', '2023-12-31']))
result = s.dt.month
print(result.tolist())
A[15, 20, 31]
B[1, 6, 12]
C[2023, 2023, 2023]
D[0, 5, 11]
Attempts:
2 left
💡 Hint
The dt accessor extracts datetime components like year, month, day.
data_output
intermediate
2:00remaining
Number of weekend days in a datetime Series
Given a pandas Series of dates, which option correctly counts how many dates fall on a weekend (Saturday or Sunday)?
Pandas
import pandas as pd
s = pd.Series(pd.to_datetime(['2023-04-01', '2023-04-02', '2023-04-03', '2023-04-04']))
weekends = s.dt.dayofweek >= 5
count = weekends.sum()
print(count)
A2
B1
C0
D3
Attempts:
2 left
💡 Hint
Dayofweek returns 0 for Monday and 6 for Sunday.
🔧 Debug
advanced
2:00remaining
Identify the error in using dt accessor
What error does this code raise?
Pandas
import pandas as pd
s = pd.Series(['2023-01-01', '2023-02-01', '2023-03-01'])
result = s.dt.day
print(result)
ANo error, prints day numbers
BTypeError: unsupported operand type(s) for -: 'str' and 'int'
CAttributeError: Can only use .dt accessor with datetimelike values
DKeyError: 'day'
Attempts:
2 left
💡 Hint
The dt accessor requires datetime type, not strings.
🚀 Application
advanced
2:00remaining
Filter rows by hour using dt accessor
You have a DataFrame with a datetime column 'timestamp'. Which code filters rows where the hour is between 9 AM and 5 PM (inclusive)?
Pandas
import pandas as pd
df = pd.DataFrame({'timestamp': pd.to_datetime(['2023-01-01 08:00', '2023-01-01 09:00', '2023-01-01 17:00', '2023-01-01 18:00'])})
Adf[(df['timestamp'].dt.hour >= 9) & (df['timestamp'].dt.hour <= 17)]
Bdf[(df['timestamp'].dt.hour > 9) & (df['timestamp'].dt.hour < 17)]
Cdf[(df['timestamp'].dt.hour >= 8) & (df['timestamp'].dt.hour <= 18)]
Ddf[(df['timestamp'].dt.hour == 9) | (df['timestamp'].dt.hour == 17)]
Attempts:
2 left
💡 Hint
Use inclusive comparison operators to include 9 AM and 5 PM.
🧠 Conceptual
expert
2:00remaining
Understanding dt accessor behavior with missing values
Given a Series with some missing datetime values, what is the output of accessing dt.day on it?
Pandas
import pandas as pd
s = pd.Series([pd.Timestamp('2023-01-01'), pd.NaT, pd.Timestamp('2023-01-03')])
result = s.dt.day
print(result.tolist())
A[1, <NA>, 3]
B[1, null, 3]
C[1, NaT, 3]
D[1, nan, 3]
Attempts:
2 left
💡 Hint
Missing datetime values become pandas NA in dt accessor outputs.