How to Subtract Days from Date in Python Easily
To subtract days from a date in Python, use the
datetime module with timedelta. Create a date object, then subtract timedelta(days=number_of_days) from it to get the new date.Syntax
Use the datetime module to work with dates. The timedelta class lets you add or subtract time intervals like days.
datetime.date(year, month, day): creates a date object.timedelta(days=n): represents a time difference of n days.- Subtract
timedeltafrom adateto get a new date.
python
from datetime import date, timedelta # Create a date object my_date = date(2024, 6, 15) # Subtract 5 days new_date = my_date - timedelta(days=5)
Example
This example shows how to subtract 10 days from June 15, 2024, and print the result.
python
from datetime import date, timedelta original_date = date(2024, 6, 15) days_to_subtract = 10 new_date = original_date - timedelta(days=days_to_subtract) print("Original date:", original_date) print("Date after subtracting days:", new_date)
Output
Original date: 2024-06-15
Date after subtracting days: 2024-06-05
Common Pitfalls
Some common mistakes when subtracting days from dates include:
- Trying to subtract an integer directly from a
dateobject (this causes an error). - Forgetting to import
timedeltafromdatetime. - Using negative days in
timedeltainstead of subtracting.
Always use timedelta(days=n) and subtract it from the date.
python
from datetime import date my_date = date(2024, 6, 15) # Wrong: causes TypeError # new_date = my_date - 5 # Right way: from datetime import timedelta new_date = my_date - timedelta(days=5) print(new_date)
Output
2024-06-10
Quick Reference
| Operation | Code Example | Description |
|---|---|---|
| Create date | date(2024, 6, 15) | Creates a date object for June 15, 2024 |
| Create timedelta | timedelta(days=5) | Represents 5 days |
| Subtract days | date - timedelta(days=5) | Subtracts 5 days from the date |
| Add days | date + timedelta(days=5) | Adds 5 days to the date |
Key Takeaways
Use datetime.date to create date objects in Python.
Subtract days by using timedelta(days=n) and subtracting it from the date.
Never subtract integers directly from date objects; always use timedelta.
Import both date and timedelta from the datetime module before use.
Subtracting days returns a new date without changing the original.