Customer A ordered on January 3 and placed two more orders on January 8. The gaps are five days and zero days. An order export may list those records out of sequence, with other customers’ orders between them.
Sort by customer and date, then use groupby().diff() to subtract the previous date within each customer. The first order you have on file for each customer gets a missing value.

Sort the orders and calculate the gaps
This example uses order dates without times and one row per order. It parses dates with an explicit format and checks that every row has a customer and a date before calculating the gaps.
import pandas as pd
orders = pd.DataFrame(
[
("A", "A109", "2026-01-20"),
("B", "B202", "2026-01-06"),
("A", "A105", "2026-01-08"),
("B", "B201", "2026-01-02"),
("A", "A101", "2026-01-03"),
("A", "A104", "2026-01-08"),
("B", "B204", "2026-01-09"),
],
columns=["customer_id", "order_id", "order_date"],
)
orders["order_date"] = pd.to_datetime(
orders["order_date"], format="%Y-%m-%d"
)
if orders[["customer_id", "order_date"]].isna().any().any():
raise ValueError("Every order needs a customer and a date.")
ordered = orders.sort_values(["customer_id", "order_date", "order_id"]).copy()
gaps = ordered.groupby("customer_id")["order_date"].diff()
ordered["days_since_previous"] = gaps.dt.days.astype("Int64")
print(ordered.to_string(index=False))
Check the result one customer at a time
| Customer | Order | Date | Days since previous |
|---|---|---|---|
| A | A101 | 2026-01-03 | <NA> |
| A | A104 | 2026-01-08 | 5 |
| A | A105 | 2026-01-08 | 0 |
| A | A109 | 2026-01-20 | 12 |
| B | B201 | 2026-01-02 | <NA> |
| B | B202 | 2026-01-06 | 4 |
| B | B204 | 2026-01-09 | 3 |
A105 follows A104 because the order ID breaks the date tie. Both orders have January 8 as their date, so the gap is zero. The tie-breaker makes the output reproducible. The dates alone cannot tell you which order happened first that day.
The grouping restarts the calculation at B201. A plain ordered["order_date"].diff() would subtract January 20 from January 2 at that boundary and produce a spurious negative gap of 18 days.
Keep the first gap missing
diff() returns timedeltas. .dt.days extracts the day count, and the nullable Int64 dtype keeps the counts as integers with <NA> where there is no previous row. Filling those gaps with zero would mix each customer’s first recorded order with genuine same-day orders.
For a report covering one month, calculate the gaps on the available history before filtering the report. A customer’s first order this month may have followed an order from the previous month. If your data has timestamps, decide whether you need elapsed time or a difference between dates in a particular time zone before subtracting.
To answer a different question with the same kind of order data, see how to group sales by month in pandas.