Dates look simple until you work with them. Is 03/04/2024 the 3rd of April or the 4th of March? Why does monthly revenue not line up with the finance team’s figures? Why did one day in March have 23 hours? Handling dates and times properly is essential for almost any business analysis, and pandas has excellent tools for it once you know how they fit together.
This tutorial covers converting text to dates (with UK formats), extracting parts of a date, date arithmetic, resampling to weekly or monthly totals, rolling averages, time zones and nearest-date joins. The examples build their own data, so you can run them immediately.
Step 1: Convert text to datetime
Data from CSV files arrives as text. Convert it with pd.to_datetime, and always specify the format for day-first UK dates:
import pandas as pd
import numpy as np
df = pd.DataFrame({"date_text": ["03/04/2024", "15/04/2024", "01/05/2024", "31/05/2024"]})
df["date"] = pd.to_datetime(df["date_text"], format="%d/%m/%Y")
print(df)
print(df.dtypes)
Common format codes: %d day, %m month number, %b short month name (Apr), %Y four-digit year, %H:%M:%S time. ISO dates such as 2024-04-03 are unambiguous and parse without a format, but being explicit never hurts.
If some values may be invalid, use errors="coerce" to turn them into NaT (missing time), then count how many failed:
raw = pd.Series(["2024-01-05", "not a date", "2024-02-30", "2024-03-01"])
parsed = pd.to_datetime(raw, format="%Y-%m-%d", errors="coerce")
print(parsed)
print("Failed to parse:", parsed.isna().sum())
Note that 30 February is correctly rejected. You can also parse dates while reading a file – see How to Read CSV Files in Pandas.
Step 2: Extract parts of a date with .dt
Once a column is a real datetime, the .dt accessor exposes its components:

df["year"] = df["date"].dt.year
df["month"] = df["date"].dt.month
df["month_name"] = df["date"].dt.month_name()
df["weekday"] = df["date"].dt.day_name()
df["is_weekend"] = df["date"].dt.dayofweek >= 5 # Monday=0, Sunday=6
df["quarter"] = df["date"].dt.quarter
df["iso_week"] = df["date"].dt.isocalendar().week
print(df.drop(columns="date_text"))
These derived columns are also useful features for machine learning – see Feature Engineering Basics.
Step 3: Date arithmetic
Subtracting two dates gives a Timedelta. Adding a Timedelta or DateOffset to a date shifts it:
orders = pd.DataFrame({
"ordered": pd.to_datetime(["2024-01-10", "2024-01-28", "2024-02-15"]),
"delivered": pd.to_datetime(["2024-01-13", "2024-02-05", "2024-02-16"]),
})
orders["days_to_deliver"] = (orders["delivered"] - orders["ordered"]).dt.days
orders["review_due"] = orders["delivered"] + pd.Timedelta(days=14)
orders["renewal"] = orders["ordered"] + pd.DateOffset(months=1)
print(orders)
Use Timedelta for fixed durations (days, hours) and DateOffset for calendar-aware steps such as months, whose lengths vary. Adding one month to 31 January gives 29 February in a leap year, not 2 March.
For working days, NumPy can count business days between dates (weekends excluded; you can pass a list of bank holidays):
bank_holidays = ["2024-01-01"]
orders["working_days"] = np.busday_count(
orders["ordered"].values.astype("datetime64[D]"),
orders["delivered"].values.astype("datetime64[D]"),
holidays=bank_holidays,
)
print(orders[["ordered", "delivered", "working_days"]])
UK bank holidays differ between England and Wales, Scotland and Northern Ireland; the official list is published on GOV.UK.
Step 4: Filter by date
rng = np.random.default_rng(0)
sales = pd.DataFrame({
"date": pd.date_range("2024-01-01", "2024-06-30", freq="D"),
})
sales["revenue"] = rng.normal(1000, 150, len(sales)).round(2)
q1 = sales[(sales["date"] >= "2024-01-01") & (sales["date"] < "2024-04-01")]
print(len(q1), "days in Q1")
s = sales.set_index("date")
print(s.loc["2024-03"].shape) # all of March
print(s.loc["2024-02-10":"2024-02-12"]) # inclusive slice
Using “greater than or equal to the start, less than the next period’s start” is the safest pattern when your data has times as well as dates, because <= "2024-03-31" would exclude everything after midnight on the 31st.
Step 5: Resample to weekly or monthly totals
resample is groupby for time. It needs a datetime index (or the on= argument):

monthly = sales.resample("MS", on="date")["revenue"].sum()
print(monthly.round(0))
weekly = sales.resample("W-MON", on="date")["revenue"].agg(["sum", "mean", "count"])
print(weekly.head())
Useful frequency codes: D day, W-MON weeks ending Monday, MS month start, ME month end, QS quarter start, YS year start. (Older pandas versions used M for month end; recent versions use ME.) Choose start or end labels to match how your organisation reports.
An alternative that many find clearer is grouping by a period: sales.groupby(sales["date"].dt.to_period("M"))["revenue"].sum().
Step 6: Rolling averages and period-on-period change
s = sales.set_index("date")["revenue"]
trend = pd.DataFrame({
"revenue": s,
"rolling_7d": s.rolling(7).mean(),
"rolling_7d_min3": s.rolling(7, min_periods=3).mean(),
})
print(trend.head(8).round(1))
m = s.resample("MS").sum()
print(m.pct_change().round(3)) # month-on-month change
A 7-day rolling mean smooths out day-of-week effects. The first six values are missing because a full window is not yet available; min_periods relaxes that. pct_change gives month-on-month growth; shift(12) on monthly data gives the same month last year for year-on-year comparisons.
Step 7: Fill gaps in a time series
Missing days are common (no sales on Sundays, sensor outages). Resampling or reindexing makes the gaps explicit:
gappy = pd.Series([5, 7, 4], index=pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-05"]))
full = gappy.reindex(pd.date_range("2024-01-01", "2024-01-05", freq="D"))
print(full)
print(full.fillna(0)) # if missing means none
print(full.interpolate()) # if missing means unrecorded
Choose the fill method based on what a missing value means: no sales is a genuine zero; a missing temperature reading is not.
Step 8: Time zones and British Summer Time
Timestamps from servers and APIs are often in UTC. UK local time switches between GMT and BST, so converting naively can shift events across midnight and into the wrong day.
utc = pd.Series(pd.to_datetime(["2024-03-30 23:30", "2024-03-31 23:30"]).tz_localize("UTC"))
london = utc.dt.tz_convert("Europe/London")
print(pd.DataFrame({"utc": utc, "london": london, "london_date": london.dt.date}))
The clocks went forward on 31 March 2024, so 23:30 UTC that evening is 00:30 on 1 April in London. If you group by date in UTC, that event counts in March; in local time it belongs to April. Decide which convention your reporting uses and apply it consistently. tz_localize attaches a time zone to naive timestamps; tz_convert converts between zones.
Step 9: Join on the nearest date with merge_asof
To attach the price in effect at the time of each order, where prices change on irregular dates, use merge_asof. Both tables must be sorted by the key:
prices = pd.DataFrame({
"effective": pd.to_datetime(["2024-01-01", "2024-02-15", "2024-04-01"]),
"unit_price": [9.99, 10.49, 10.99],
})
ords = pd.DataFrame({
"ordered": pd.to_datetime(["2024-01-20", "2024-02-15", "2024-03-30", "2024-04-02"]),
"units": [3, 1, 2, 5],
})
priced = pd.merge_asof(ords.sort_values("ordered"), prices.sort_values("effective"),
left_on="ordered", right_on="effective", direction="backward")
print(priced)
Each order gets the most recent price on or before its date. For ordinary key matching, see Merging and Joining DataFrames in Pandas.
Worked example: which weekday sells most?
Combining the steps above answers a typical question in a few lines. We take the daily sales series, add a weekday name, and average revenue by weekday in the natural Monday-to-Sunday order rather than alphabetically:
order = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
by_day = (sales.assign(weekday=pd.Categorical(sales["date"].dt.day_name(), categories=order, ordered=True))
.groupby("weekday", observed=True)["revenue"]
.agg(["mean", "count"])
.round(1))
print(by_day)
Using an ordered categorical makes the output sort correctly, which matters when you chart it. The count column is a quick check that every weekday has a similar number of observations; if one weekday had far fewer (because of bank holidays, say), its average would be less reliable. Our sample data is random, so you should not expect a real pattern here – but on genuine sales data, this simple table is often one of the most useful first views.
Common mistakes
- Letting pandas guess day-first vs month-first. Specify
format. - Leaving dates as text, so sorting is alphabetical and resampling fails.
- Using
<= end_datewhen values include times. - Mixing UTC and local time, especially around clock changes.
- Filling all gaps with zero when missing does not mean zero.
- Comparing partial periods, such as a half-finished current month against complete months.
FAQ
How do I format a date as text for a report?
Use df["date"].dt.strftime("%d %b %Y"), which gives values such as “03 Apr 2024”.
What is the difference between Timestamp and Period?
A Timestamp is a point in time; a Period is a span, such as the whole of April 2024. Periods are convenient for monthly reporting labels.
How do I get the start of the week or month for each date?
df["date"].dt.to_period("M").dt.start_time gives the first day of the month; use "W-SUN" for weeks ending Sunday (starting Monday).
How do I handle financial years starting in April?
Use period frequencies anchored to March year-end, for example dt.to_period("Q-MAR") for quarters, or compute year - (month < 4) for the financial year start.
Next steps
Summarise time-based data with pandas groupby, visualise trends with Matplotlib Basics, and compare date handling in SQL with SQL GROUP BY and HAVING.



