0
0
PandasHow-ToBeginner · 3 min read

How to Add Days to Date in Pandas: Simple Guide

To add days to a date in pandas, use pd.to_timedelta() with the number of days and add it to your date column or Series. For example, df['date'] + pd.to_timedelta(5, unit='d') adds 5 days to each date.
📐

Syntax

The basic syntax to add days to a pandas date column is:

  • df['date_column'] + pd.to_timedelta(number_of_days, unit='d')

Here, df['date_column'] is your pandas Series with dates, number_of_days is how many days you want to add, and unit='d' means days.

python
df['date_column'] + pd.to_timedelta(3, unit='d')
💻

Example

This example shows how to add 7 days to each date in a pandas DataFrame column.

python
import pandas as pd

dates = pd.to_datetime(['2024-01-01', '2024-02-15', '2024-03-10'])
df = pd.DataFrame({'date': dates})

# Add 7 days to each date

df['date_plus_7'] = df['date'] + pd.to_timedelta(7, unit='d')

print(df)
Output
date date_plus_7 0 2024-01-01 2024-01-08 1 2024-02-15 2024-02-22 2 2024-03-10 2024-03-17
⚠️

Common Pitfalls

One common mistake is trying to add an integer directly to a pandas datetime column, which causes an error. You must use pd.to_timedelta() to specify the time unit.

Wrong way:

df['date'] + 5  # This will raise an error

Right way:

df['date'] + pd.to_timedelta(5, unit='d')
python
import pandas as pd

dates = pd.to_datetime(['2024-01-01'])
df = pd.DataFrame({'date': dates})

# Wrong way (raises error)
# df['date'] + 5

# Correct way
result = df['date'] + pd.to_timedelta(5, unit='d')
print(result)
Output
0 2024-01-06 Name: date, dtype: datetime64[ns]
📊

Quick Reference

Here is a quick cheat sheet for adding time to pandas dates:

OperationCode ExampleDescription
Add daysdf['date'] + pd.to_timedelta(3, unit='d')Add 3 days to each date
Add hoursdf['date'] + pd.to_timedelta(5, unit='h')Add 5 hours to each date/time
Add minutesdf['date'] + pd.to_timedelta(10, unit='m')Add 10 minutes
Add secondsdf['date'] + pd.to_timedelta(30, unit='s')Add 30 seconds

Key Takeaways

Use pd.to_timedelta() to add days to pandas datetime columns safely.
Adding an integer directly to datetime columns causes errors.
Specify the unit as 'd' for days when using pd.to_timedelta().
You can add other time units like hours, minutes, and seconds similarly.
Always ensure your date column is in datetime format before adding days.