HomeCourseModule 10 › Working with dates in pandas

Working with dates in pandas

Module 10 · Data Cleaning and Transformation9 min readBeginner

What you'll learn

  • Convert string columns to datetime
  • Pull year/month/day/weekday from a date column
  • Resample a time series

Parse first

df["date"] = pd.to_datetime(df["date"], errors="coerce")

errors="coerce" turns unparsable strings into NaT (missing date) instead of crashing.

Pull parts out

df["year"]   = df["date"].dt.year
df["month"]  = df["date"].dt.month
df["dow"]    = df["date"].dt.day_name()         # 'Saturday'
df["q"]      = df["date"].dt.to_period("Q")     # PeriodIndex 2026Q2
df["month_start"] = df["date"].dt.to_period("M").dt.to_timestamp()

Date arithmetic

df["days_open"] = (df["closed"] - df["opened"]).dt.days
df["due_date"] = df["created"] + pd.Timedelta(days=30)
df[df["date"] >= "2026-01-01"]

Resampling (group by time bucket)

monthly = (df.set_index("date")["amount"]
             .resample("M")
             .sum())

weekly  = df.set_index("date")["amount"].resample("W").mean()

Walkthrough: monthly revenue trend

Parse and group

df["date"] = pd.to_datetime(df["date"])
monthly = (df.groupby(df["date"].dt.to_period("M"))["amount"]
             .sum()
             .reset_index())
monthly["date"] = monthly["date"].astype(str)

Save / plot

monthly.to_excel("monthly_revenue.xlsx", index=False)

Key takeaways

  • pd.to_datetime(..., errors="coerce") is the safe parse.
  • .dt gives you year, month, day, day_name, to_period.
  • .resample("M") on a datetime index gives quick time-bucket aggregates.

Weekly average

From a transactions DataFrame with date + amount, compute the average daily revenue per week of the year.

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.