Calculate elapsed days, weeks, hours and seconds, filter durations and review missing or reversed dates.
Show Table of Contents ↓import pandas as pd
import numpy as np
df = pd.DataFrame({"NAME": ["Ravi", "Raju", "Alex"],
"dt_start": pd.to_datetime(["2020-01-01", "2020-02-01", "2020-05-01"]),
"dt_end": pd.to_datetime(["2022-06-15", "2022-07-22", "2023-11-15"])})
df["difference"] = df["dt_end"] - df["dt_start"]
print(df)
assert df["difference"].dt.days.tolist() == [896, 902, 1293]Expected output
NAME dt_start dt_end difference
0 Ravi 2020-01-01 2022-06-15 896 days
1 Raju 2020-02-01 2022-07-22 902 days
2 Alex 2020-05-01 2023-11-15 1293 daysdf["diff_days"] = df["difference"] / np.timedelta64(1, "D")
print(df[["NAME", "diff_days"]])
filtered = df.loc[df["diff_days"].gt(900), ["NAME", "diff_days"]]
print(filtered)
assert filtered["NAME"].tolist() == ["Raju", "Alex"]Expected output
NAME diff_days
0 Ravi 896.0
1 Raju 902.0
2 Alex 1293.0
NAME diff_days
1 Raju 902.0
2 Alex 1293.0weeks = df["difference"] / np.timedelta64(1, "W")
print(weeks.tolist())
print("Whole weeks:", weeks.astype("int64").tolist())
assert weeks.astype("int64").tolist() == [128, 128, 184]Expected output
[128.0, 128.85714285714286, 184.71428571428572]
Whole weeks: [128, 128, 184]for unit, label in [("h", "Hours"), ("m", "Minutes"), ("s", "Seconds")]:
result = df["difference"] / np.timedelta64(1, unit)
print(label, result.tolist())
seconds = df["difference"].dt.total_seconds()
assert seconds.iloc[0] == 896 * 86400
assert seconds.equals(df["difference"] / np.timedelta64(1, "s"))Expected output
Hours [21504.0, 21648.0, 31032.0]
Minutes [1290240.0, 1298880.0, 1861920.0]
Seconds [77414400.0, 77932800.0, 111715200.0]for unit in ["ms", "us", "ns"]:
result = df["difference"] / np.timedelta64(1, unit)
print(unit, result.tolist())
short = pd.Timedelta(microseconds=123)
assert short / np.timedelta64(1, "us") == 123Expected output
ms [77414400000.0, 77932800000.0, 111715200000.0]
us [77414400000000.0, 77932800000000.0, 111715200000000.0]
ns [7.74144e+16, 7.79328e+16, 1.117152e+17]durations = pd.Series(pd.to_timedelta(["1 days 12 hours", "-12 hours"]))
print("Fractional days:", (durations / np.timedelta64(1, "D")).tolist())
print("Day components:", durations.dt.days.tolist())
print("Second remainders:", durations.dt.seconds.tolist())
assert durations.dt.days.tolist() == [1, -1]
assert durations.dt.total_seconds().tolist() == [129600.0, -43200.0]Expected output
Fractional days: [1.5, -0.5]
Day components: [1, -1]
Second remainders: [43200, 43200]events = pd.DataFrame({"start": ["2026-09-05 09:00", "2026-09-05 11:00", None],
"end": ["2026-09-05 10:30", "2026-09-05 10:00", "2026-09-05 12:00"]})
for column in ["start", "end"]:
events[column] = pd.to_datetime(events[column], format="%Y-%m-%d %H:%M", errors="coerce", utc=True)
events["elapsed"] = events["end"] - events["start"]
valid = events["elapsed"].notna() & events["elapsed"].ge(pd.Timedelta(0))
accepted = events.loc[valid].copy()
review = events.loc[~valid].copy()
print("Accepted minutes:", (accepted["elapsed"] / np.timedelta64(1, "m")).tolist())
print("Review rows:", review.index.tolist())
assert len(accepted) == 1 and len(review) == 2Expected output
Accepted minutes: [90.0]
Review rows: [1, 2]jan = pd.Timestamp("2026-01-31")
calendar_month = jan + pd.DateOffset(months=1)
fixed_days = jan + pd.Timedelta(days=30)
print(calendar_month)
print(fixed_days)
assert calendar_month != fixed_daysExpected output
2026-02-28 00:00:00
2026-03-02 00:00:00| NumPy unit | Meaning |
|---|---|
W | Seven-day week |
D | 24-hour elapsed day |
h | Hour |
m | Minute |
s | Second |
ms | Millisecond |
us | Microsecond |
ns | Nanosecond |
Use lowercase m for minutes, not M (month). Calendar dates and elapsed 24-hour durations differ across daylight-saving changes. Make timezone interpretation explicit before subtraction. Check missing and negative durations before integer conversion. For a pure Pandas alternative divide by pd.Timedelta(days=1). Do not assume integer timedelta storage is always nanoseconds.
sample = pd.Series(pd.to_timedelta([45, 90, 150], unit="min"))
chosen = sample.loc[sample.gt(pd.Timedelta(hours=1))]
minutes = chosen / np.timedelta64(1, "m")
print(minutes.tolist())
assert minutes.tolist() == [90.0, 150.0]Expected output
[90.0, 150.0]Open in Google Colab View on GitHub
Run examples in order, inspect formatted dates and try the exercise. Save a copy to keep edits.
Reference: Pandas Date differences documentation.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.