The dt accessor helps you easily get parts of dates and times from your data. It makes working with dates simple and clear.
dt accessor for datetime properties in Pandas
dataframe['date_column'].dt.propertydate_column must be a datetime type for dt to work.
Common properties include year, month, day, hour, weekday, and more.
date column.df['date'].dt.yeardf['date'].dt.monthdf['date'].dt.weekdaydf['date'].dt.hourThis code creates a table with dates and extracts different parts like year, month, day, weekday number, and hour into new columns.
import pandas as pd data = {'date': ['2023-01-15 08:30:00', '2023-06-20 14:45:00', '2023-12-25 00:00:00']} df = pd.DataFrame(data) df['date'] = pd.to_datetime(df['date']) # Extract year, month, day, weekday, and hour df['year'] = df['date'].dt.year df['month'] = df['date'].dt.month df['day'] = df['date'].dt.day df['weekday'] = df['date'].dt.weekday df['hour'] = df['date'].dt.hour print(df)
If your date column is not datetime type, use pd.to_datetime() to convert it first.
The weekday property counts Monday as 0 and Sunday as 6.
You can also use dt.day_name() to get the weekday name as text.
The dt accessor lets you get parts of dates easily.
Use it to extract year, month, day, hour, weekday, and more.
Make sure your data is in datetime format before using dt.
Practice
What does the dt accessor in pandas allow you to do?
Solution
Step 1: Understand the purpose of
Thedtaccessordtaccessor is used with datetime columns to access their components like year, month, day, etc.Step 2: Compare options with this purpose
Only Extract parts like year, month, and day from datetime columns describes extracting parts of datetime, which matches thedtaccessor's use.Final Answer:
Extract parts like year, month, and day from datetime columns -> Option AQuick Check:
dtaccessor = extract datetime parts [OK]
- Thinking dt converts strings to numbers
- Confusing dt with sorting functions
- Assuming dt creates random data
Which of the following is the correct syntax to get the month from a pandas datetime column df['date']?
df['date']?.monthSolution
Step 1: Recall correct dt accessor syntax
To access datetime parts, use.dtfollowed by the property without parentheses.Step 2: Check each option
df['date'].dt.month uses.dt.monthcorrectly. df['date'].month() wrongly uses parentheses. df['date'].dt('month') uses wrong syntax. df['date'].month.dt reverses order.Final Answer:
df['date'].dt.month -> Option BQuick Check:
Use.dt.propertysyntax [OK]
- Calling month as a function with ()
- Using dt as a function
- Reversing dt and property order
Given the following code, what will be the output?
import pandas as pd
dates = pd.Series(pd.to_datetime(['2023-01-15', '2023-07-20', '2023-12-31']))
months = dates.dt.month
print(months.tolist())Solution
Step 1: Understand the code
The code creates a Series of datetime objects for three dates, then extracts the month number usingdt.month.Step 2: Determine the month numbers
January is month 1, July is 7, December is 12, so the list is [1, 7, 12].Final Answer:
[1, 7, 12] -> Option CQuick Check:
dt.month extracts month numbers [OK]
- Confusing day with month
- Expecting month names instead of numbers
- Printing year instead of month
What is wrong with this code snippet?
import pandas as pd
dates = pd.Series(['2023-01-15', '2023-07-20'])
print(dates.dt.day)Solution
Step 1: Check the data type of the Series
The Series contains strings, not datetime objects, sodtaccessor cannot be used directly.Step 2: Identify the error cause
Without converting to datetime usingpd.to_datetime(), accessingdt.dayraises an error.Final Answer:
The Series is not converted to datetime before using dt accessor -> Option AQuick Check:
Convert to datetime before using dt [OK]
- Assuming dt works on string Series
- Thinking dt.day does not exist
- Ignoring data type requirements
You have a DataFrame df with a datetime column 'timestamp'. You want to create a new column 'is_weekend' that is True if the date is Saturday or Sunday, and False otherwise. Which code correctly does this?
df['is_weekend'] = df['timestamp'].dt.weekday > 4Solution
Step 1: Understand weekday numbering
In pandas,dt.weekdayreturns 0 for Monday up to 6 for Sunday. Weekend days are 5 (Saturday) and 6 (Sunday).Step 2: Check each option's logic
df['is_weekend'] = df['timestamp'].dt.weekday > 4 uses > 4, which means days 5 and 6 are True. df['is_weekend'] = df['timestamp'].dt.day > 4 checks day of month, not weekday. df['is_weekend'] = df['timestamp'].dt.weekday == 5 or 6 uses incorrect syntax for or. df['is_weekend'] = df['timestamp'].dt.weekday in [5, 6] uses 'in' which is invalid for Series.Final Answer:
df['is_weekend'] = df['timestamp'].dt.weekday > 4 -> Option DQuick Check:
Weekend days have weekday > 4 [OK]
- Using day instead of weekday
- Wrong boolean logic with or
- Using 'in' with pandas Series
Ready to prove it?
Pass the test and this pattern moves unknown
