Dates and times

to_datetime, the .dt accessor, timedeltas, and grouping by period.

Store timestamps as datetime64, then use the .dt accessor. Do not parse dates in a Python loop. Do not leave them as strings if you need month, weekday, or filters.

Goal

Parse mixed date strings, pull year/month, filter a range, and group by period.

raw = pd.Series(
    ["2024-01-03", "2024/02/15", "2024-03-01", "not-a-date", "2024-04-10"],
    name="joined",
)
print(raw)

to_datetime

parsed = pd.to_datetime(raw, errors="coerce", format="mixed")
print(parsed)
print(parsed.dtype)

errors="coerce" turns garbage into NaT (missing time). format="mixed" lets pandas infer per-value formats (ISO vs YYYY/MM/DD). If every value shares one format, pass it (format="%Y-%m-%d") — faster and stricter.

.dt pieces

A datetime Series needs .dt. A Timestamp scalar uses .year directly.

s = pd.to_datetime(["2024-01-03", "2024-02-15", "2024-03-01", "2024-04-10"])
print(
    pd.DataFrame(
        {
            "date": s,
            "year": s.dt.year,
            "month": s.dt.month,
            "day": s.dt.day,
            "weekday": s.dt.day_name(),
            "quarter": s.dt.quarter,
        }
    )
)
print()
print("first year (scalar):", s.iloc[0].year)

Filter a range

df = pd.DataFrame({
    "date": pd.to_datetime(["2024-01-03", "2024-02-15", "2024-03-01", "2024-04-10"]),
    "units": [12, 7, 5, 9],
})
start = pd.Timestamp("2024-02-01")
end = pd.Timestamp("2024-03-31")
print(df[df["date"].between(start, end)])

Timedelta

df = pd.DataFrame({
    "start": pd.to_datetime(["2024-01-03", "2024-02-01"]),
    "end": pd.to_datetime(["2024-01-08", "2024-02-11"]),
})
df["days"] = (df["end"] - df["start"]).dt.days
print(df)

Group by month

df = pd.DataFrame({
    "date": pd.to_datetime(
        ["2024-01-03", "2024-01-20", "2024-02-02", "2024-02-18", "2024-03-04"]
    ),
    "revenue": [126.0, 42.0, 242.0, 176.0, 52.5],
})
print(df.groupby(df["date"].dt.to_period("M"))["revenue"].sum())
Tip

After you upload sales_log.csv, parse date once and reuse it: df["date"] = pd.to_datetime(df["date"]).