Complete the code to convert the 'date_str' column to datetime format using 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'])
The pd.to_datetime() function converts string dates into pandas datetime objects.
Complete the code to parse dates with a specific format 'dd/mm/yyyy' using to_datetime().
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'])
The format parameter uses Python's datetime format codes. '%d/%m/%Y' matches day/month/year with slashes.
Fix the error in the code to correctly parse dates with errors ignored.
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'])
The errors='coerce' option converts invalid parsing to NaT (missing datetime), avoiding errors.
Fill both blanks to create a dictionary of dates and their weekday names from a list of date strings.
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)
date which returns the date, not weekdayday which returns day of month, not weekdaydt.weekday gives the day number (0=Monday), and dt.day_name() gives the weekday name as a string.
Fill all three blanks to create a filtered DataFrame with dates after '2023-01-31' and add a new column with formatted dates.
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)
Use > to filter dates after '2023-01-31'. The strftime method formats dates as strings.