The dt accessor in pandas provides a variety of attributes and methods to work with datetime objects. Here are some commonly used dt accessors:
dt.year: Extracts the year from the datetime.dt.month: Extracts the month from the datetime.dt.day: Extracts the day of the month from the datetime.dt.hour: Extracts the hour from the datetime.dt.minute: Extracts the minute from the datetime.dt.second: Extracts the second from the datetime.dt.weekday: Returns the day of the week as an integer (Monday=0, Sunday=6).dt.dayofweek: Similar todt.weekday, returns the day of the week.dt.is_month_end: Returns a boolean indicating if the date is the last day of the month.dt.is_month_start: Returns a boolean indicating if the date is the first day of the month.dt.quarter: Extracts the quarter of the year (1 to 4).dt.days_in_month: Returns the number of days in the month.dt.strftime(format): Formats the datetime as a string according to the specified format.
Example Usage:
import pandas as pd
# Sample DataFrame with a datetime column
data = {
'datetime': ['2023-10-01', '2023-10-15', '2023-11-05']
}
df = pd.DataFrame(data)
df['datetime'] = pd.to_datetime(df['datetime'])
# Using various dt accessors
df['year'] = df['datetime'].dt.year
df['month'] = df['datetime'].dt.month
df['day'] = df['datetime'].dt.day
df['weekday'] = df['datetime'].dt.weekday
df['is_month_end'] = df['datetime'].dt.is_month_end
print(df)
This example demonstrates how to use several dt accessors to extract different components and properties from a datetime column.
