typestar

Dates in Python

Parse to datetime once, then the .dt accessor answers everything else.

import pandas as pd

frame = pd.DataFrame({
    "day": ["2026-07-27", "2026-07-28", "2026-08-02"],
    "tpm": [91, 104, 97],
})
frame["day"] = pd.to_datetime(frame["day"])

print(frame["day"].dt.day_name().tolist())
print(frame["day"].dt.month.tolist())

indexed = frame.set_index("day")
print(indexed.loc["2026-07"])

How it works

  1. to_datetime handles most formats; pass format for speed.
  2. .dt exposes year, month, day name and more.
  3. Setting a DatetimeIndex unlocks time-based slicing.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
309
Tokens
118
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 64 seconds.

Type this snippet

Step 1 of 3 in Time series, step 23 of 26 in pandas.

← Previous Next →

Dates in other languages