Sub topic 6
Indexing and slicing with a DatetimeIndex
This chapter assumes you can create pandas Series and DataFrames, select with .loc, filter rows with boolean masks, and convert text to datetimes with pd.to_datetime. If a column still holds strings, convert it first.
A DatetimeIndex is an index whose labels are timestamps. It lets you select rows with date strings, slice by date range, and filter by time of day. The sections below cover each of these and the edge cases that cause wrong results.
Building a DatetimeIndex
The usual route is to parse a column and then move it into the index. Sort the index afterwards, because slicing depends on order.
import pandas as pd
df = pd.DataFrame({
"when": ["2024-03-02 14:45", "2024-03-01 09:30", "2024-03-05 08:00"],
"amount": [25, 10, 40],
})
df["when"] = pd.to_datetime(df["when"], format="%Y-%m-%d %H:%M")
ts = df.set_index("when")["amount"].sort_index()
print(type(ts.index).__name__)
print(ts.index.is_monotonic_increasing)is_monotonic_increasing is True when the labels are in ascending order. Check it whenever a slice returns something surprising.
You can also create an index directly with pd.date_range, which later chapters cover in detail. The examples below use a daily series and an hourly series.
import pandas as pd
daily = pd.Series(
range(30),
index=pd.date_range("2023-12-20", periods=30, freq="D"),
name="value",
)
hourly = pd.Series(
range(72),
index=pd.date_range("2024-01-02", periods=72, freq="h"),
name="reading",
)The daily series runs from 2023-12-20 to 2024-01-18. The hourly series runs from 2024-01-02 00:00 to 2024-01-04 23:00. The lowercase "h" alias needs pandas 2.2 or later. On older versions, write "H".
Partial string indexing
With a DatetimeIndex, you can pass a string that names only part of a date. pandas reads it as a span of time and returns every row inside that span.
print(daily.loc["2024"])
print(daily.loc["2024-01"])
print(hourly.loc["2024-01-03"])daily.loc["2024"]returns every row in 2024, which is 18 rows.daily.loc["2024-01"]returns every row in January 2024, also 18 rows here.hourly.loc["2024-01-03"]returns all 24 hourly rows of January 3.
The same strings work on a DataFrame whose index is a DatetimeIndex.
frame = pd.DataFrame(
{"sales": range(30), "units": range(30, 60)},
index=daily.index,
)
print(frame.loc["2024-01"])
print(frame.loc["2024-01-05":"2024-01-08", "sales"])When a string is a span and when it is an exact label
The result depends on how precise the string is compared with the index.
- If the string is less precise than the index, pandas treats it as a span. A day string on an hourly index returns many rows.
- If the string is as precise as the index, pandas treats it as an exact label. A day string on a daily index returns one value.
print(daily.loc["2024-01-03"])
print(daily.loc["2024-01-03":"2024-01-03"])The first line prints a single number, which is the scalar value. The second prints a one-row Series. When you want the result to always be a Series, use a slice. The same applies to a DataFrame, where an exact match returns a row as a Series.
Slicing by date range
A slice with : selects everything between two points. Unlike integer slicing, label slicing includes both ends.
print(daily.loc["2023-12-28":"2024-01-02"])
print(daily.loc["2024-01-15":])
print(daily.loc[:"2023-12-22"])With partial strings, the end covers its whole span. This surprises many people.
print(len(hourly.loc["2024-01-02":"2024-01-03"]))This prints 48. The end string "2024-01-03" means the whole of January 3, so the slice runs to 2024-01-03 23:00.
Strings versus Timestamp objects
A pd.Timestamp is an exact instant, so it never expands into a span.
start = pd.Timestamp("2024-01-02")
end = pd.Timestamp("2024-01-03")
print(len(hourly.loc[start:end]))This prints 25. The slice includes 2024-01-03 00:00 and nothing later that day. If you want the whole last day, use a string end or add the time yourself, for example pd.Timestamp("2024-01-03 23:59:59").
| Selector | Meaning | Rows on the hourly series |
|---|---|---|
| `"2024-01-03"` | The whole day | 24 |
| `"2024-01-02":"2024-01-03"` | Both days, whole | 48 |
| `Timestamp("2024-01-02"):Timestamp("2024-01-03")` | From midnight Jan 2 to midnight Jan 3 | 25 |
Choosing a selection method
Selecting by time of day
Slices work on whole dates. To select by clock time across all days, use between_time and at_time. Both require a DatetimeIndex.
print(hourly.between_time("09:00", "11:00"))
print(hourly.at_time("12:00"))between_time includes both ends by default, so it returns 3 rows per day, 9 in total. at_time returns one row per day at exactly that time. You can control the ends with the inclusive argument, for example inclusive="left".
Selecting by calendar properties
A DatetimeIndex exposes the same components as the .dt accessor, but directly as attributes. Compare them to build a boolean mask.
mondays = daily[daily.index.dayofweek == 0]
january = daily[daily.index.month == 1]
print(mondays)
print(january.index.min(), january.index.max())dayofweek counts Monday as 0 and Sunday as 6. Use a mask for rules that a contiguous slice cannot express, such as "every Monday" or "the first day of each month".
Filtering when dates are in a column
If you have not moved the dates into the index, a boolean mask works. pandas converts a string on the right side of the comparison into a timestamp.
events = pd.DataFrame({
"when": pd.to_datetime(["2024-03-01", "2024-03-02", "2024-03-05"]),
"amount": [10, 25, 40],
})
mask = (events["when"] >= "2024-03-02") & (events["when"] < "2024-03-06")
print(events[mask])Comparisons are exact, not partial. events["when"] <= "2024-03-05" means "up to midnight at the start of March 5". Rows later that day are excluded. The pattern >= start and < day_after_end is safer, and it works the same on any resolution.
Edge cases and failure modes
Unsorted index
Slicing a non-monotonic index can fail or return a surprising result. If an endpoint is not an exact label in the index, pandas may raise a KeyError about partial slicing on a non-monotonic index. Call sort_index() first.
Duplicate timestamps
An index can contain the same timestamp more than once. An exact label then returns all matching rows as a Series, not a scalar. Code that expects a scalar can break when new data introduces duplicates. Check with ts.index.has_duplicates.
Time zone mismatch
For a time-zone-aware index, strings are read in the index's own time zone. A naive Timestamp compared with an aware index raises an error. Either use strings, or give the Timestamp a zone with pd.Timestamp("2024-01-03", tz="UTC").
Missing labels
A single exact label that is not in the index raises KeyError. A slice with endpoints that fall between labels does not. On a sorted index it returns whatever lies between them, and returns an empty Series if nothing does. When you need to know where a date would sit, use searchsorted.
pos = daily.index.searchsorted(pd.Timestamp("2024-01-03 12:00"))
print(pos, daily.index[pos])This prints the integer position of the first label at or after the given instant, followed by that label (2024-01-04).
Quick reference
| Task | Code |
|---|---|
| Whole year or month | `s.loc["2024"]`, `s.loc["2024-01"]` |
| Date range, both ends included | `s.loc["2024-01-05":"2024-01-08"]` |
| Everything from a date onward | `s.loc["2024-01-15":]` |
| Time of day window | `s.between_time("09:00", "17:00")` |
| Single time every day | `s.at_time("12:00")` |
| Weekday filter | `s[s.index.dayofweek < 5]` |
| Check order | `s.index.is_monotonic_increasing` |
Exercise
An hourly Series covers 2024-01-02 00:00 to 2024-01-04 23:00. How many rows does s.loc["2024-01-02":"2024-01-03"] return, and how many does s.loc[pd.Timestamp("2024-01-02"):pd.Timestamp("2024-01-03")] return? Explain the difference.
Show answer
The string slice returns 48 rows, because the end string "2024-01-03" covers the whole day, up to 23:00. The Timestamp slice returns 25 rows, because a Timestamp is an exact instant. It stops at 2024-01-03 00:00 and includes that one row.
Exercise
You have a daily Series d with a DatetimeIndex. Write one expression that returns only the rows that fall on a weekday (Monday to Friday) in February 2024. Then say why you should not write d.loc["2024-02-01":"2024-02-29"] if you only want weekdays.
Show answer
d.loc["2024-02"][d.loc["2024-02"].index.dayofweek < 5] works, and so does w = d.loc["2024-02"]; w[w.index.dayofweek < 5]. The slice d.loc["2024-02-01":"2024-02-29"] selects a contiguous range, so it includes weekends. A slice can only express a span of time. A rule such as "weekdays only" needs a boolean mask built from index.dayofweek.