Bird
Raised Fist0
Pandasdata~20 mins

Datetime type in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Datetime Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this pandas datetime conversion?
Given the following code, what will be the output of df['date_converted'].dtype?
Pandas
import pandas as pd

df = pd.DataFrame({'date_str': ['2023-01-01', '2023-06-15', '2023-12-31']})
df['date_converted'] = pd.to_datetime(df['date_str'])
print(df['date_converted'].dtype)
Adatetime64[ns]
Bobject
Cstring
Dint64
Attempts:
2 left
💡 Hint
Think about what type pandas uses to store datetime values internally.
❓ data_output
intermediate
2:00remaining
What is the output of extracting the year from datetime?
What will be the output of df['year'] after running this code?
Pandas
import pandas as pd

df = pd.DataFrame({'dates': pd.to_datetime(['2022-05-20', '2023-07-15', '2024-01-01'])})
df['year'] = df['dates'].dt.year
print(df['year'].tolist())
A['2022', '2023', '2024']
B[2022, 2023, 2024]
C[5, 7, 1]
D[20, 15, 1]
Attempts:
2 left
💡 Hint
The dt.year extracts the year as an integer from datetime values.
🔧 Debug
advanced
2:00remaining
Why does this code raise an error?
This code tries to convert a column to datetime but raises an error. What is the cause?
Pandas
import pandas as pd

df = pd.DataFrame({'dates': ['2023-01-01', 'not_a_date', '2023-03-01']})
df['dates_converted'] = pd.to_datetime(df['dates'])
AValueError because 'not_a_date' cannot be converted to datetime
BTypeError because the column is not a string type
CKeyError because 'dates_converted' column does not exist yet
DSyntaxError due to missing parentheses
Attempts:
2 left
💡 Hint
Check if all strings in the column are valid date formats.
❓ visualization
advanced
3:00remaining
Which plot shows the count of dates by month correctly?
Given this DataFrame, which option produces a bar plot showing counts of dates grouped by month?
Pandas
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'dates': pd.to_datetime(['2023-01-15', '2023-01-20', '2023-02-10', '2023-02-15', '2023-03-01'])})
A
df['month'] = df['dates'].dt.month
counts = df.groupby('month').size()
counts.plot(kind='line')
plt.show()
B
df['month'] = df['dates'].month
counts = df['month'].count()
counts.plot(kind='bar')
plt.show()
C
df['month'] = df['dates'].dt.month
counts = df['month'].value_counts()
counts.plot(kind='pie')
plt.show()
D
df['month'] = df['dates'].dt.month
counts = df['month'].value_counts().sort_index()
counts.plot(kind='bar')
plt.show()
Attempts:
2 left
💡 Hint
Use dt.month and count values grouped by month, then plot a bar chart.
🧠 Conceptual
expert
3:00remaining
What is the effect of timezone conversion on pandas datetime?
If a pandas datetime column is timezone-naive and you convert it to a timezone-aware datetime with dt.tz_localize('UTC'), what happens?
AThe datetime values become strings with timezone info appended
BThe datetime values are shifted to UTC time adjusting the clock time accordingly
CThe datetime values are treated as UTC time without changing the clock time, adding timezone info
DThe datetime values raise an error because timezone-naive cannot be localized
Attempts:
2 left
💡 Hint
Localizing adds timezone info without changing the actual time values.

Practice

(1/5)
1. What is the main purpose of the Datetime type in pandas?
easy
A. To store images and multimedia files
B. To store only text data
C. To store dates and times in a format pandas can understand and work with
D. To store numerical data like integers and floats

Solution

  1. Step 1: Understand what Datetime type stores

    Datetime type is designed to hold date and time information in a structured way.
  2. Step 2: Compare with other data types

    Unlike text or numbers, Datetime allows easy date calculations and filtering.
  3. Final Answer:

    To store dates and times in a format pandas can understand and work with -> Option C
  4. Quick Check:

    Datetime type = stores dates/times [OK]
Hint: Datetime type is for dates and times only [OK]
Common Mistakes:
  • Thinking Datetime stores text or numbers
  • Confusing Datetime with string type
  • Assuming Datetime stores images
2. Which of the following is the correct way to convert a string column df['date_str'] to datetime type in pandas?
easy
A. df['date_str'].astype('datetime')
B. pd.to_datetime(df['date_str'])
C. df['date_str'].to_datetime()
D. pd.datetime(df['date_str'])

Solution

  1. Step 1: Recall the pandas function for datetime conversion

    The correct function is pd.to_datetime() to convert strings to datetime.
  2. Step 2: Check the options for correct syntax

    Only pd.to_datetime(df['date_str']) uses pd.to_datetime() correctly with the column.
  3. Final Answer:

    pd.to_datetime(df['date_str']) -> Option B
  4. Quick Check:

    Use pd.to_datetime() for conversion [OK]
Hint: Use pd.to_datetime() to convert strings to datetime [OK]
Common Mistakes:
  • Using astype('datetime') which is invalid
  • Calling to_datetime() as a method on Series
  • Using pd.datetime which does not exist
3. What will be the output of this code?
import pandas as pd
s = pd.Series(['2023-01-01', '2023-02-15', 'not a date'])
s_dt = pd.to_datetime(s, errors='coerce')
s_dt.isna().sum()
medium
A. 0
B. Raises an error
C. 2
D. 1

Solution

  1. Step 1: Convert strings to datetime with errors='coerce'

    The invalid string 'not a date' becomes NaT (missing datetime).
  2. Step 2: Count missing datetime values

    Only one value is invalid, so isna().sum() returns 1.
  3. Final Answer:

    1 -> Option D
  4. Quick Check:

    Invalid dates become NaT, count is 1 [OK]
Hint: errors='coerce' makes invalid dates NaT [OK]
Common Mistakes:
  • Expecting error instead of NaT
  • Counting all as valid dates
  • Confusing NaT with zero
4. The following code throws an error. What is the mistake?
import pandas as pd
s = pd.Series(['2023-01-01', '2023-02-15'])
s_dt = s.to_datetime()
medium
A. Series object has no method to_datetime()
B. pd.to_datetime() requires a list, not Series
C. Missing import for datetime module
D. Strings are not in correct date format

Solution

  1. Step 1: Check method usage on Series

    Series does not have a method called to_datetime().
  2. Step 2: Correct method to convert Series to datetime

    Use pd.to_datetime(s) instead of s.to_datetime().
  3. Final Answer:

    Series object has no method to_datetime() -> Option A
  4. Quick Check:

    Use pd.to_datetime(), not s.to_datetime() [OK]
Hint: Use pd.to_datetime(), not Series.to_datetime() [OK]
Common Mistakes:
  • Trying to call to_datetime() on Series
  • Assuming pd.to_datetime() needs list input
  • Thinking import datetime is required here
5. You have a DataFrame df with a column 'date_str' containing dates as strings in mixed formats like '2023-01-01', '01/02/2023', and 'March 3, 2023'. How do you convert this column to datetime type reliably?
hard
A. Use pd.to_datetime(df['date_str'], errors='coerce')
B. Use pd.to_datetime(df['date_str'], errors='coerce', dayfirst=true)
C. Use df['date_str'].astype('datetime64')
D. Use pd.to_datetime(df['date_str'], errors='ignore')

Solution

  1. Step 1: Understand mixed date formats and errors

    Mixed formats can cause parsing errors; using errors='coerce' converts unparseable dates to NaT safely.
  2. Step 2: Evaluate options for handling mixed formats

    Use pd.to_datetime(df['date_str'], errors='coerce') uses pd.to_datetime() with errors='coerce', which is reliable for mixed formats without forcing dayfirst.
  3. Final Answer:

    Use pd.to_datetime(df['date_str'], errors='coerce') -> Option A
  4. Quick Check:

    errors='coerce' handles mixed formats safely [OK]
Hint: Use errors='coerce' to handle mixed date formats safely [OK]
Common Mistakes:
  • Using errors='ignore' which keeps strings unconverted
  • Using astype('datetime64') which fails on mixed formats
  • Setting dayfirst=true incorrectly for all dates
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