Bird
Raised Fist0
Pandasdata~10 mins

to_datetime() for parsing dates in Pandas - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to convert the 'date_str' column to datetime format using pandas.

Pandas
import pandas as pd

df = pd.DataFrame({'date_str': ['2023-01-01', '2023-02-15', '2023-03-20']})
df['date'] = pd.[1](df['date_str'])
print(df['date'])
Drag options to blanks, or click blank then click option'
Ato_date
Bto_datetime
Cdatetime_parse
Dparse_date
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-existent function like pd.to_date()
Trying to convert without using pandas functions
2fill in blank
medium

Complete the code to parse dates with a specific format 'dd/mm/yyyy' using to_datetime().

Pandas
import pandas as pd

dates = ['31/12/2023', '01/01/2024', '15/02/2024']
df = pd.DataFrame({'dates': dates})
df['parsed'] = pd.to_datetime(df['dates'], format=[1])
print(df['parsed'])
Drag options to blanks, or click blank then click option'
A'%d/%m/%Y'
B'%m-%d-%Y'
C'yyyy-mm-dd'
D'dd/mm/yyyy'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong format string like 'yyyy-mm-dd'
Not using percent signs (%) in the format string
3fill in blank
hard

Fix the error in the code to correctly parse dates with errors ignored.

Pandas
import pandas as pd

dates = ['2023-01-01', 'not a date', '2023-03-15']
df = pd.DataFrame({'dates': dates})
df['parsed'] = pd.to_datetime(df['dates'], errors=[1])
print(df['parsed'])
Drag options to blanks, or click blank then click option'
A'raise'
B'ignore'
C'coerce'
D'skip'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'ignore' which returns original data without conversion
Using 'raise' which throws an error on invalid dates
4fill in blank
hard

Fill both blanks to create a dictionary of dates and their weekday names from a list of date strings.

Pandas
import pandas as pd

dates = ['2023-04-01', '2023-04-02', '2023-04-03']
df = pd.DataFrame({'dates': dates})
df['dates'] = pd.to_datetime(df['dates'])
weekday_dict = dict(zip(df['dates'].dt.[1], df['dates'].dt.[2]()))
print(weekday_dict)
Drag options to blanks, or click blank then click option'
Adate
Bday_name
Cweekday
Dday
Attempts:
3 left
💡 Hint
Common Mistakes
Using date which returns the date, not weekday
Using day which returns day of month, not weekday
5fill in blank
hard

Fill all three blanks to create a filtered DataFrame with dates after '2023-01-31' and add a new column with formatted dates.

Pandas
import pandas as pd

dates = ['2023-01-15', '2023-02-10', '2023-03-05']
df = pd.DataFrame({'dates': dates})
df['dates'] = pd.to_datetime(df['dates'])
filtered = df[df['dates'] [1] pd.Timestamp([2])]
filtered['formatted'] = filtered['dates'].dt.[3]('%Y/%m/%d')
print(filtered)
Drag options to blanks, or click blank then click option'
A>
B'2023-01-31'
Cstrftime
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' for filtering
Passing date as a string without quotes
Using a non-existent method instead of strftime

Practice

(1/5)
1. What does the pandas.to_datetime() function do?
easy
A. It filters rows based on date values.
B. It converts text or numbers into date objects.
C. It sorts data in ascending order.
D. It converts numbers into strings.

Solution

  1. Step 1: Understand the purpose of to_datetime()

    This function is used to change text or numbers that represent dates into actual date objects that pandas can understand.
  2. Step 2: Compare options with the function's purpose

    Only It converts text or numbers into date objects. correctly describes this conversion. Other options describe unrelated operations.
  3. Final Answer:

    It converts text or numbers into date objects. -> Option B
  4. Quick Check:

    to_datetime() = converts to dates [OK]
Hint: to_datetime() changes strings/numbers into dates [OK]
Common Mistakes:
  • Thinking it sorts data
  • Confusing it with string conversion
  • Assuming it filters data
2. Which of the following is the correct syntax to convert a column named 'date_str' in DataFrame df to datetime using pandas?
easy
A. df['date_str'] = pd.to_datetime(df['date_str'])
B. df.to_datetime('date_str')
C. pd.to_datetime(df.date_str, inplace=True)
D. df['date_str'].to_datetime()

Solution

  1. Step 1: Identify the correct function call

    The function pd.to_datetime() is called with the column as argument to convert it.
  2. Step 2: Check assignment to the DataFrame column

    The converted datetime values must be assigned back to the column to update it, which df['date_str'] = pd.to_datetime(df['date_str']) does correctly.
  3. Final Answer:

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

    Use pd.to_datetime() and assign back [OK]
Hint: Use pd.to_datetime(column) and assign back [OK]
Common Mistakes:
  • Calling to_datetime as a DataFrame method
  • Using inplace parameter which does not exist
  • Not assigning the result back to the column
3. What will be the output of this code?
import pandas as pd
s = pd.Series(['01-12-2023', '02-11-2023'])
dates = pd.to_datetime(s, dayfirst=True)
print(dates.dt.month.tolist())
medium
A. [2, 1]
B. [1, 2]
C. [11, 12]
D. [12, 11]

Solution

  1. Step 1: Understand the input strings and dayfirst=True

    The strings are '01-12-2023' and '02-11-2023'. With dayfirst=True, '01-12-2023' means 1st December 2023 (month=12), and '02-11-2023' means 2nd November 2023 (month=11).
  2. Step 2: Extract the month values

    Using dates.dt.month.tolist() extracts the month numbers as a list: [12, 11].
  3. Final Answer:

    [12, 11] -> Option D
  4. Quick Check:

    dayfirst=True swaps day and month [OK]
Hint: dayfirst=True means day is first in date string [OK]
Common Mistakes:
  • Ignoring dayfirst and reading month first
  • Mixing up month numbers
  • Confusing string format with default parsing
4. Identify the error in this code snippet:
import pandas as pd
s = pd.Series(['2023/12/01', '2023/11/02'])
dates = pd.to_datetime(s, format='%Y-%m-%d')
print(dates)
medium
A. The to_datetime function requires dayfirst=True here.
B. The Series should be converted using astype('datetime64').
C. The format string does not match the date strings.
D. The date strings are missing time information.

Solution

  1. Step 1: Compare date strings with format string

    The date strings use slashes '/' like '2023/12/01', but the format string expects dashes '-' as in '%Y-%m-%d'. This mismatch causes a parsing error.
  2. Step 2: Understand the impact of format mismatch

    Because the format does not match the input, pandas will raise an error or fail to parse correctly.
  3. Final Answer:

    The format string does not match the date strings. -> Option C
  4. Quick Check:

    Format must match date string exactly [OK]
Hint: Match format string exactly to date string separators [OK]
Common Mistakes:
  • Using wrong separators in format
  • Assuming astype converts strings to dates
  • Adding dayfirst when not needed
5. You have a DataFrame df with a column 'date_str' containing dates in mixed formats like '2023-12-01' and '01/12/2023'. How can you convert this column to datetime correctly?
hard
A. Use pd.to_datetime(df['date_str'], dayfirst=True, errors='coerce') to parse with day first and convert errors to NaT.
B. Use pd.to_datetime(df['date_str'], format='%Y-%m-%d') to force one format.
C. Use df['date_str'].astype('datetime64') to convert automatically.
D. Use pd.to_datetime(df['date_str'], exact=true) to parse exactly.

Solution

  1. Step 1: Understand mixed date formats

    Since the column has mixed formats (ISO and day/month/year), specifying a single format will fail for some entries.
  2. Step 2: Use flexible parsing with dayfirst=True and handle errors

    Using dayfirst=True helps interpret dates like '01/12/2023' correctly. Setting errors='coerce' converts unparseable dates to NaT instead of error.
  3. Step 3: Avoid forcing a single format or using astype

    Forcing a format or using astype will cause errors or wrong parsing with mixed formats.
  4. Final Answer:

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

    Flexible parsing with dayfirst and error handling [OK]
Hint: Use dayfirst=True and errors='coerce' for mixed formats [OK]
Common Mistakes:
  • Forcing a single format on mixed data
  • Using astype for string to datetime
  • Ignoring errors causing exceptions
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