DateTime Parsing, Indexing & .dt Accessor0%
DateTime Parsing, Indexing & .dt Accessor
Beginner12 min read•Updated: Jul 11, 2026
DateTime Parsing, Indexing & .dt Accessor
Reading Time: 8 Mins | Level: Beginner to Advanced
1. Working with Time in Pandas
In real-world business analytics (sales trends, stock prices, churn tracking, server logs), dates are central. Pandas provides the native datetime64[ns] dtype and DatetimeIndex for high-performance temporal computations.
2. Converting Strings to Datetime (pd.to_datetime)
Python
import pandas as pd
date_strings = ['2026-01-15', '2026-02-20', '2026-03-25']
dt_series = pd.to_datetime(date_strings)
print(dt_series)
Parsing Non-Standard Date Formats:
Python
# Indian date format: DD/MM/YYYY
raw_dates = pd.Series(['15/08/2026', '26/01/2026', '02/10/2026'])
# Pass exact strptime format
clean_dates = pd.to_datetime(raw_dates, format='%d/%m/%Y')
print(clean_dates)
3. The .dt Accessor (Extracting Date Components)
Just as strings have the .str accessor, dates have the .dt accessor for extracting year, month, day, weekday, quarter, etc.:
Python
df = pd.DataFrame({'Timestamp': clean_dates})
df['Year'] = df['Timestamp'].dt.year
df['Month'] = df['Timestamp'].dt.month
df['Month_Name'] = df['Timestamp'].dt.month_name()
df['Day'] = df['Timestamp'].dt.day
df['Day_of_Week'] = df['Timestamp'].dt.day_name()
df['Is_Weekend'] = df['Timestamp'].dt.dayofweek >= 5
print(df)
4. The DatetimeIndex & Date Slicing
Promoting a Datetime column to the DataFrame Index unlocks powerful partial-string date slicing:
Python
df_sales = pd.DataFrame({
'Revenue': [15000, 22000, 31000]
}, index=pd.to_datetime(['2026-01-05', '2026-01-20', '2026-02-14']))
# Slice all transactions from January 2026 using simple string notation!
jan_sales = df_sales.loc['2026-01']
print(jan_sales)
Interactive Quiz
Multiple Choice Questions
Question 1
Which function converts strings or Unix epoch integers into Pandas DateTime objects?
Question 2
What accessor is used to extract date properties (such as year, month, and day_name) from a DateTime Series?
Question 3
How do you extract the name of the day of the week (e.g. 'Monday', 'Tuesday') from a DateTime column?
Question 4
What format string parses a date formatted as "25-Dec-2026"?
Question 5
What unique capability is enabled when setting a
DatetimeIndex as the DataFrame's index?Next Lesson
Resampling, Rolling Windows & Shifting
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Reshaping Data: Melt, Stack & Unstack | Resampling, Rolling Windows & Shifting |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.