What other dt accessors exist?

QuestionsQuestions8 SkillsProHandling Time Series DataAug, 06 2025
0153

The dt accessor in pandas provides a variety of attributes and methods to work with datetime objects. Here are some commonly used dt accessors:

  1. dt.year: Extracts the year from the datetime.
  2. dt.month: Extracts the month from the datetime.
  3. dt.day: Extracts the day of the month from the datetime.
  4. dt.hour: Extracts the hour from the datetime.
  5. dt.minute: Extracts the minute from the datetime.
  6. dt.second: Extracts the second from the datetime.
  7. dt.weekday: Returns the day of the week as an integer (Monday=0, Sunday=6).
  8. dt.dayofweek: Similar to dt.weekday, returns the day of the week.
  9. dt.is_month_end: Returns a boolean indicating if the date is the last day of the month.
  10. dt.is_month_start: Returns a boolean indicating if the date is the first day of the month.
  11. dt.quarter: Extracts the quarter of the year (1 to 4).
  12. dt.days_in_month: Returns the number of days in the month.
  13. 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.

0 Comments

no data
Be the first to share your comment!