Pandas Date Differences with NumPy timedelta64

Calculate elapsed days, weeks, hours and seconds, filter durations and review missing or reversed dates.

Create the original sample dates 🔝

The original Ravi, Raju and Alex dates are retained using explicit ISO inputs. Subtracting datetime columns produces a Timedelta Series; np.timedelta64 creates a duration scalar. This sample is synthetic practice data.
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 days

Convert to numeric days and filter 🔝

Divide by one day to retain fractional days. The original rule selects durations greater than 900 days. Use to_datetime() to parse source text before subtraction.
df["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.0

Convert to weeks and count whole weeks 🔝

W represents seven elapsed days. For nonnegative known durations, conversion to integer truncates the fractional part. For signed durations decide between floor and truncation rather than silently choosing.
weeks = 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]

Hours, minutes and seconds 🔝

NumPy minute units use lowercase m, unlike datetime formatting %M. Dividing by a unit avoids assuming a specific internal storage resolution.
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]

Milliseconds, microseconds and nanoseconds 🔝

The original small-unit conversions are retained. Large numeric durations returned as floating point can lose exact integer precision; do not use them as exact identifiers.
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") == 123

Expected 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]

Compare dt.days with fractional days 🔝

dt.days returns the floor day component. It differs from fractional days, especially for negative durations. total_seconds() measures the whole duration, whereas dt.seconds is a remainder within a day.
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]

Keep missing and reversed dates for review 🔝

This synthetic workflow accepts only known nonnegative elapsed durations. Preserve missing or reversed rows instead of casting them to integers or replacing them with zero.
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) == 2

Expected output

Accepted minutes: [90.0]
Review rows: [1, 2]

Calendar months and years are not fixed units 🔝

Do not divide Pandas durations by NumPy M or Y to count calendar months or years. NumPy can represent these units, but they do not define a fixed number of days. Use DateOffset() for calendar arithmetic or relativedelta() for a specified calendar-difference convention.
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_days

Expected output

2026-02-28 00:00:00
2026-03-02 00:00:00

Unit reference and pitfalls 🔝

NumPy unitMeaning
WSeven-day week
D24-hour elapsed day
hHour
mMinute
sSecond
msMillisecond
usMicrosecond
nsNanosecond

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.

Exercise: elapsed time threshold 🔝

Create durations of 45, 90 and 150 minutes. Select those strictly greater than one hour and verify their numeric minute values. Continue with Date and Time exercises or the basics exercises.

Exercise solution 🔝

Compare durations before converting to display units.
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]

Practice in Google Colab 🔝

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.




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer