← Back to Pandas Course | Chapter 10: Time Series | Lesson 2 of 7

DatetimeIndex

A DatetimeIndex makes dates the row labels, unlocking slicing by date strings and time-based tools.

In this page:

  1. DatetimeIndex
Syntax
python
df["date"] = pd.to_datetime(df["date"])
df = df.set_index("date")
df.loc["2024-03"]

DatetimeIndex

Set a datetime column as the index with set_index after converting it. Then you can slice with strings like df["2024-01"] or df["2024-01-05":"2024-01-10"]. Index properties such as .month and .dayofweek are available directly.

Note: Partial string indexing such as df.loc["2024-02"] selects a whole month.

Example: DatetimeIndex

python
import pandas as pd

df = pd.DataFrame({"date": pd.to_datetime(["2024-01-05", "2024-01-20", "2024-02-03"]), "sales": [10, 20, 30]}).set_index("date")
print(df.loc["2024-01"])
print(df.index.month.tolist())

# Output:
#             sales
# date
# 2024-01-05     10
# 2024-01-20     20
# [1, 1, 2]
Related Topics
Common Mistakes
  1. Forgetting to convert to datetime first
  2. Unsorted index slicing
  3. Using a text column as the index
Chapter Summary
  • Convert then set_index
  • Slice with date strings
  • Partial strings select periods
  • Index exposes month and dayofweek
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.