Date arithmetic with timedelta in Pandas - Time & Space Complexity
We want to understand how the time it takes to do date calculations changes as we work with more dates.
Specifically, how does adding or subtracting time from many dates affect the work done?
Analyze the time complexity of the following code snippet.
import pandas as pd
from datetime import timedelta
dates = pd.date_range('2023-01-01', periods=1000)
delta = timedelta(days=5)
new_dates = dates + delta
This code creates 1000 dates and adds 5 days to each date.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding a fixed time difference to each date in the list.
- How many times: Once for each date, so 1000 times in this example.
When we add a time difference to each date, the work grows as we have more dates.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of dates. Double the dates, double the work.
Time Complexity: O(n)
This means the time to add a timedelta grows in a straight line with the number of dates.
[X] Wrong: "Adding a timedelta to a list of dates happens instantly regardless of list size."
[OK] Correct: Each date must be updated one by one, so more dates mean more work and more time.
Understanding how operations scale with data size helps you write efficient code and explain your choices clearly.
"What if we added a different timedelta to each date instead of the same one? How would the time complexity change?"
Practice
pd.Timedelta(days=3) represent in pandas?Solution
Step 1: Understand Timedelta purpose
pd.Timedeltais used to represent a duration or difference in time, not a fixed date or time.Step 2: Interpret the argument
The argumentdays=3means the duration is 3 days long.Final Answer:
A time difference of 3 days -> Option CQuick Check:
Timedelta(days=3) = 3 days [OK]
- Thinking Timedelta is a fixed date
- Confusing Timedelta with Timestamp
- Assuming it returns a string
ts?Solution
Step 1: Check correct Timedelta syntax
The correct way to specify 5 days ispd.Timedelta(days=5). The argument must be named or a valid string.Step 2: Verify addition syntax
Adding a Timedelta to a Timestamp uses the+operator, sots + pd.Timedelta(days=5)is correct.Final Answer:
ts + pd.Timedelta(days=5) -> Option DQuick Check:
Correct syntax uses days=5 inside Timedelta [OK]
- Missing quotes or wrong argument format
- Using add() method incorrectly
- Passing string without units
import pandas as pd
start = pd.Timestamp('2024-01-01')
new_date = start + pd.Timedelta(days=10) - pd.Timedelta(days=3)
print(new_date.strftime('%Y-%m-%d'))Solution
Step 1: Calculate addition of 10 days
Starting from 2024-01-01, adding 10 days gives 2024-01-11.Step 2: Subtract 3 days from the result
Subtracting 3 days from 2024-01-11 results in 2024-01-08.Final Answer:
2024-01-08 -> Option AQuick Check:
2024-01-01 + 10 - 3 days = 2024-01-08 [OK]
- Adding and subtracting days in wrong order
- Miscounting days
- Confusing string formatting output
import pandas as pd
start = pd.Timestamp('2024-05-01')
new_date = start + pd.Timedelta(5)
print(new_date)Solution
Step 1: Check Timedelta argument
pd.Timedelta(5)is missing the unit. It needs a keyword likedays=5or a string like'5 days'.Step 2: Understand error cause
Without specifying units, pandas cannot interpret the number 5 alone, causing an error.Final Answer:
Timedelta needs a unit like days=5 -> Option AQuick Check:
Timedelta(5) missing units causes error [OK]
- Passing integer without units
- Assuming default unit is days
- Confusing Timestamp and Timedelta usage
df with a column 'date' of type datetime. You want to create a new column 'date_plus_7' that adds 7 days to each date. Which code correctly does this?Solution
Step 1: Understand Timedelta broadcasting
Adding a Timedelta to a pandas Series of dates works if the Timedelta is a scalar (single duration).Step 2: Check each option
df['date_plus_7'] = df['date'] + pd.Timedelta('7 days') uses a string '7 days' which works but is less common in vectorized operations. df['date_plus_7'] = df['date'] + pd.Timedelta(days=7) usespd.Timedelta(days=7)which is the standard and recommended way. df['date_plus_7'] = df['date'] + pd.Timedelta(7) misses units and causes error. df['date_plus_7'] = df['date'] + pd.Timedelta(days=7) * len(df) multiplies timedelta by length, which incorrectly scales the timedelta.Step 3: Choose the best practice
df['date_plus_7'] = df['date'] + pd.Timedelta(days=7) is the correct and recommended way to add 7 days to each date in a column.Final Answer:
df['date_plus_7'] = df['date'] + pd.Timedelta(days=7) -> Option BQuick Check:
Use pd.Timedelta(days=7) for vectorized addition with Series [OK]
- Passing integer without units
- Multiplying Timedelta by length of DataFrame
- Not using vectorized Timedelta correctly
Ready to prove it?
Pass the test and this pattern moves unknown
