Sales per day, tickets per hour, sign-ups per week: much business data is a time series. pandas has excellent tools for it once your dates are proper datetime values.
The examples use a fictional bike-rental service, PedalPoint, with a rides table: ride_id, start_time, station, minutes, fare.
Step 1: make sure dates are dates
import pandas as pd
rides = pd.read_csv("rides.csv", parse_dates=["start_time"])
rides["start_time"].dtype # should be datetime64For messy text dates, use pd.to_datetime(col, dayfirst=True, errors="coerce") and check how many became NaT.
Step 2: extract parts
rides["date"] = rides["start_time"].dt.date
rides["hour"] = rides["start_time"].dt.hour
rides["weekday"] = rides["start_time"].dt.day_name()
rides["month"] = rides["start_time"].dt.to_period("M")Great for "which hour is busiest?" questions with groupby("hour").
Step 3: resample to a regular frequency
daily = rides.set_index("start_time").resample("D")["fare"].sum()
weekly_rides = rides.set_index("start_time").resample("W")["ride_id"].count()
monthly = rides.set_index("start_time").resample("MS")["fare"].sum() # month start labelsresample is groupby for time. A big advantage: days with no rides appear with zero (for sums and counts) instead of disappearing, so charts do not silently skip gaps.
Step 4: smooth with rolling windows
daily_7d = daily.rolling(7).mean()
daily_7d_centered = daily.rolling(7, center=True).mean()A seven-day rolling average removes weekday-weekend swings and shows the underlying trend. The first six values are NaN because there is not enough history yet.
Step 5: compare periods
monthly_change = monthly.pct_change() # vs previous month
yoy = monthly.pct_change(12) # vs same month last year
previous = monthly.shift(1) # previous month's value alongsidepct_change returns fractions; multiply by 100 for percentages.
Cumulative totals
ytd = monthly.groupby(monthly.index.year).cumsum()Time zones, briefly
Timestamps from apps are often stored in UTC. Convert before analysing hours of the day:
rides["start_time"] = rides["start_time"].dt.tz_localize("UTC").dt.tz_convert("Asia/Kolkata")Otherwise your "busiest hour" may be off by five and a half hours.
Plotting
ax = daily.plot(alpha=0.4, label="Daily")
daily_7d.plot(ax=ax, label="7-day average")
ax.legend()Showing raw daily values faintly with a bold rolling average is a clear, common pattern.
Common mistakes
- Grouping by month number alone and merging months from different years.
- Comparing a partial current month with full previous months.
- Forgetting that rolling windows need sorted dates.
Practise
Our dates and time series set covers parsing, resampling, rolling windows and period comparisons, and the line charts set helps you present them.
Practise what you just read
Reading helps; writing the code yourself is what sticks. Start here: