How do you subtract days from a date or datetime object in Python? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you subtract days from a date or datetime object in Python?

message-square
0

Instantiate datetime.timedelta(days=n) from the built-in datetime module and subtract it directly from a date or datetime object (dt - timedelta(days=7)), which automatically handles month boundaries, year rollovers, and leap years.

Basic Example

from datetime import date, datetime, timedelta, timezone

# 1. Subtract days from a `date` object:
today = date(2026, 3, 2)
five_days_ago = today - timedelta(days=5)
print(five_days_ago)
# Output: 2026-02-25 (automatically handles Feb 28 in non-leap year 2026)

# 2. Subtract days (and hours/minutes) from a timezone-aware `datetime` object:
now_utc = datetime(2026, 11, 29, 17, 25, tzinfo=timezone.utc)
cutoff = now_utc - timedelta(days=10, hours=4)
print(cutoff.isoformat())
# Output: 2026-11-19T13:25:00+00:00

# 3. Adding a negative timedelta works identically:
print(today + timedelta(days=-5))
# Output: 2026-02-25

Key Details & Edge Cases

  • timedelta supports weeks, days, hours, minutes, seconds, milliseconds, and microseconds—NOT months or years:
    • Because months and years vary in length (28–31 days, 365–366 days), timedelta(months=1) raises TypeError: 'months' is an invalid keyword argument for this function. When you need calendar month/year arithmetic (e.g., 2026-03-31 minus 1 month $\rightarrow$ 2026-02-28), use dateutil.relativedelta(months=1) (pip install python-dateutil).
  • Daylight Saving Time (DST) nuance on timezone-aware datetime objects (zoneinfo.ZoneInfo):
    • Subtracting timedelta(days=1) subtracts an exact 24-hour duration (86,400 seconds). Across a DST spring-forward or fall-back transition, local_dt - timedelta(days=1) may shift the wall-clock hour by 1 hour (e.g., 09:00 $\rightarrow$ 10:00).
    • If you want the same wall-clock time on the previous calendar day across DST transitions, subtract timedelta(days=1) in UTC and convert back, or use dateutil.relativedelta(days=1) / ZoneInfo:
      from zoneinfo import ZoneInfo
      
      ny = ZoneInfo("America/New_York")
      dt = datetime(2026, 11, 2, 9, 0, tzinfo=ny)  # Day after US fall-back DST
      exact_24h_ago = dt - timedelta(days=1)        # 2026-11-01 10:00:00-04:00 (24h duration)
      
  • Supported timedelta range and overflow:
    • timedelta supports values from -999999999 days up to +999999999 days, and subtracting past date.min (0001-01-01) or adding past date.max (9999-12-31) raises OverflowError: date value out of range.
  • Vectorized day subtraction in Pandas (pd.Timedelta):
    • On a Pandas datetime64 column, subtract pd.Timedelta(days=7) (or pd.to_timedelta(df["offset_days"], unit="D") for per-row offsets):
      df["start_date"] = df["end_date"] - pd.Timedelta(days=7)
      

Comparison of Date & Datetime Subtraction Methods in Python

Method Library Supports days / hours? Supports Calendar months / years? Best Used When
dt - timedelta(days=n) (Recommended) Built-in datetime Yes (weeks, days, hours, minutes, seconds) No All standard day/week/hour offsets on date and datetime objects with zero external dependencies.
dt - relativedelta(days=n) python-dateutil (3rd-party) Yes Yes (months=1, years=1 with end-of-month clamping) Business billing cycles, subscriptions, or calendar-month/year offsets where month length varies.
df["col"] - pd.Timedelta(days=n) pandas Yes No (use pd.DateOffset(months=n)) Vectorized date arithmetic across entire DataFrame columns.
dt.replace(day=dt.day - n) (Avoid) Built-in datetime Unsafe No Never use for arithmetic—raises ValueError: day is out of range for month whenever dt.day - n <= 0.