DatetimeIndex
A DatetimeIndex makes dates the row labels, unlocking slicing by date strings and time-based tools.
In this page:
Syntax
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
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
- Forgetting to convert to datetime first
- Unsorted index slicing
- 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: