0
0
PythonHow-ToBeginner · 3 min read

How to Add Days to Date in Python Easily

To add days to a date in Python, use the datetime module's timedelta class. Create a timedelta object with the number of days to add, then add it to a date or datetime object.
📐

Syntax

Use the datetime module. Create a timedelta object with days, then add it to a date or datetime object.

  • from datetime import date, timedelta: imports needed classes.
  • timedelta(days=n): creates a time difference of n days.
  • date + timedelta: adds days to the date.
python
from datetime import date, timedelta

start_date = date(2024, 6, 1)
days_to_add = 5
new_date = start_date + timedelta(days=days_to_add)
print(new_date)
Output
2024-06-06
💻

Example

This example shows how to add 10 days to today's date and print the new date.

python
from datetime import datetime, timedelta

# Get current date and time
now = datetime.now()

# Add 10 days
future_date = now + timedelta(days=10)

print("Today:", now.strftime('%Y-%m-%d'))
print("After 10 days:", future_date.strftime('%Y-%m-%d'))
Output
Today: 2024-06-07 After 10 days: 2024-06-17
⚠️

Common Pitfalls

One common mistake is trying to add an integer directly to a date or datetime object, which causes an error. Always use timedelta to add days.

Also, remember that timedelta can add negative days to subtract days.

python
from datetime import date

start_date = date(2024, 6, 1)

# Wrong way - causes TypeError
# new_date = start_date + 5  # This will raise an error

# Right way
from datetime import timedelta
new_date = start_date + timedelta(days=5)
print(new_date)
Output
2024-06-06
📊

Quick Reference

OperationCode ExampleDescription
Add daysdate + timedelta(days=5)Adds 5 days to a date
Subtract daysdate - timedelta(days=3)Subtracts 3 days from a date
Create timedeltatimedelta(days=10)Creates a 10-day time difference
Get todaydate.today()Gets current date

Key Takeaways

Use datetime.timedelta to add or subtract days from a date.
Never add integers directly to date or datetime objects.
timedelta supports negative values to subtract days.
Use datetime.date or datetime.datetime objects for date operations.
Always import timedelta from the datetime module before use.