Bird
Raised Fist0
Pandasdata~20 mins

Date arithmetic with timedelta in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Date Arithmetic Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Adding timedelta to a pandas Series of dates
What is the output of this code snippet?
Pandas
import pandas as pd
from datetime import timedelta

dates = pd.Series(pd.to_datetime(['2024-01-01', '2024-01-02', '2024-01-03']))
result = dates + timedelta(days=3)
print(result)
A
0   2024-01-04
1   2024-01-05
2   2024-01-06
dtype: datetime64[ns]
B
0   2024-01-01
1   2024-01-02
2   2024-01-03
dtype: datetime64[ns]
CTypeError: unsupported operand type(s) for +: 'Series' and 'timedelta.timedelta'
D
0   2024-01-04 00:00:00
1   2024-01-05 00:00:00
2   2024-01-06 00:00:00
dtype: datetime64[ns]
Attempts:
2 left
💡 Hint
Try adding a timedelta object directly to a pandas Series of datetime values.
❓ data_output
intermediate
2:00remaining
Subtracting timedelta from a DataFrame column
Given this DataFrame, what is the output of subtracting 5 hours from the 'timestamp' column?
Pandas
import pandas as pd
from datetime import timedelta

df = pd.DataFrame({'timestamp': pd.to_datetime(['2024-06-01 12:00', '2024-06-01 15:00'])})
df['new_time'] = df['timestamp'] - timedelta(hours=5)
print(df['new_time'])
A
0   2024-06-01 07:00:00
1   2024-06-01 10:00:00
Name: new_time, dtype: datetime64[ns]
B
0   2024-06-01 17:00:00
1   2024-06-01 20:00:00
Name: new_time, dtype: datetime64[ns]
CTypeError: unsupported operand type(s) for -: 'Series' and 'timedelta.timedelta'
D
0   2024-06-01 12:00:00
1   2024-06-01 15:00:00
Name: new_time, dtype: datetime64[ns]
Attempts:
2 left
💡 Hint
Subtracting timedelta decreases the datetime values by the specified duration.
🔧 Debug
advanced
2:00remaining
Identify the error in timedelta addition to a DataFrame
What error does this code produce and why?
Pandas
import pandas as pd
from datetime import timedelta

df = pd.DataFrame({'date': ['2024-01-01', '2024-01-02']})
df['date'] = df['date'] + timedelta(days=1)
print(df)
ATypeError: unsupported operand type(s) for +: 'Series' and 'timedelta.timedelta'
BValueError: could not convert string to datetime
CNo error, dates incremented by 1 day
DAttributeError: 'list' object has no attribute 'dt'
Attempts:
2 left
💡 Hint
Check the data type of the 'date' column before adding timedelta.
🚀 Application
advanced
2:00remaining
Calculate the difference in days between two date columns
Given this DataFrame, which option correctly creates a new column 'diff_days' showing the number of days between 'end_date' and 'start_date'?
Pandas
import pandas as pd

df = pd.DataFrame({
    'start_date': pd.to_datetime(['2024-01-01', '2024-01-10']),
    'end_date': pd.to_datetime(['2024-01-05', '2024-01-15'])
})
A
df['diff_days'] = df['end_date'] - df['start_date']
print(df['diff_days'])
B
df['diff_days'] = (df['end_date'] - df['start_date']).dt.days
print(df['diff_days'])
C
df['diff_days'] = (df['start_date'] - df['end_date']).days
print(df['diff_days'])
D
df['diff_days'] = (df['end_date'] + df['start_date']).dt.days
print(df['diff_days'])
Attempts:
2 left
💡 Hint
Subtracting datetime columns gives a timedelta Series; use .dt.days to get integer days.
🧠 Conceptual
expert
2:00remaining
Understanding timedelta behavior with mixed frequency data
You have a pandas Series with timestamps at irregular intervals. You add a timedelta of 1 day to this Series. What happens to the timestamps that fall on daylight saving time change days?
AA ValueError is raised because timedelta cannot handle daylight saving changes.
BThe timestamps shift by 23 or 25 hours depending on the daylight saving change.
CThe timestamps shift by exactly 24 hours regardless of daylight saving changes.
DThe timestamps remain unchanged because timedelta ignores irregular intervals.
Attempts:
2 left
💡 Hint
Timedelta represents a fixed duration, not calendar-aware shifts.

Practice

(1/5)
1. What does pd.Timedelta(days=3) represent in pandas?
easy
A. A string describing 3 days
B. A specific date 3 days from now
C. A time difference of 3 days
D. A timestamp at 3 AM

Solution

  1. Step 1: Understand Timedelta purpose

    pd.Timedelta is used to represent a duration or difference in time, not a fixed date or time.
  2. Step 2: Interpret the argument

    The argument days=3 means the duration is 3 days long.
  3. Final Answer:

    A time difference of 3 days -> Option C
  4. Quick Check:

    Timedelta(days=3) = 3 days [OK]
Hint: Timedelta means duration, not a fixed date [OK]
Common Mistakes:
  • Thinking Timedelta is a fixed date
  • Confusing Timedelta with Timestamp
  • Assuming it returns a string
2. Which of the following is the correct way to add 5 days to a pandas Timestamp ts?
easy
A. ts.add(pd.Timedelta(5))
B. ts + pd.Timedelta('5')
C. ts + pd.Timedelta(5 days)
D. ts + pd.Timedelta(days=5)

Solution

  1. Step 1: Check correct Timedelta syntax

    The correct way to specify 5 days is pd.Timedelta(days=5). The argument must be named or a valid string.
  2. Step 2: Verify addition syntax

    Adding a Timedelta to a Timestamp uses the + operator, so ts + pd.Timedelta(days=5) is correct.
  3. Final Answer:

    ts + pd.Timedelta(days=5) -> Option D
  4. Quick Check:

    Correct syntax uses days=5 inside Timedelta [OK]
Hint: Use named argument days=5 inside Timedelta [OK]
Common Mistakes:
  • Missing quotes or wrong argument format
  • Using add() method incorrectly
  • Passing string without units
3. What is the output of this code?
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'))
medium
A. 2024-01-08
B. 2024-01-13
C. 2024-01-04
D. 2024-01-10

Solution

  1. Step 1: Calculate addition of 10 days

    Starting from 2024-01-01, adding 10 days gives 2024-01-11.
  2. Step 2: Subtract 3 days from the result

    Subtracting 3 days from 2024-01-11 results in 2024-01-08.
  3. Final Answer:

    2024-01-08 -> Option A
  4. Quick Check:

    2024-01-01 + 10 - 3 days = 2024-01-08 [OK]
Hint: Add then subtract days stepwise to find final date [OK]
Common Mistakes:
  • Adding and subtracting days in wrong order
  • Miscounting days
  • Confusing string formatting output
4. The following code throws an error. What is the problem?
import pandas as pd
start = pd.Timestamp('2024-05-01')
new_date = start + pd.Timedelta(5)
print(new_date)
medium
A. Timedelta needs a unit like days=5
B. Timestamp cannot be added to Timedelta
C. pd.Timedelta requires string input only
D. Missing import for Timedelta

Solution

  1. Step 1: Check Timedelta argument

    pd.Timedelta(5) is missing the unit. It needs a keyword like days=5 or a string like '5 days'.
  2. Step 2: Understand error cause

    Without specifying units, pandas cannot interpret the number 5 alone, causing an error.
  3. Final Answer:

    Timedelta needs a unit like days=5 -> Option A
  4. Quick Check:

    Timedelta(5) missing units causes error [OK]
Hint: Always specify units when creating Timedelta [OK]
Common Mistakes:
  • Passing integer without units
  • Assuming default unit is days
  • Confusing Timestamp and Timedelta usage
5. You have a pandas DataFrame 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?
hard
A. df['date_plus_7'] = df['date'] + pd.Timedelta('7 days')
B. df['date_plus_7'] = df['date'] + pd.Timedelta(days=7)
C. df['date_plus_7'] = df['date'] + pd.Timedelta(7)
D. df['date_plus_7'] = df['date'] + pd.Timedelta(days=7) * len(df)

Solution

  1. Step 1: Understand Timedelta broadcasting

    Adding a Timedelta to a pandas Series of dates works if the Timedelta is a scalar (single duration).
  2. 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) uses pd.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.
  3. 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.
  4. Final Answer:

    df['date_plus_7'] = df['date'] + pd.Timedelta(days=7) -> Option B
  5. Quick Check:

    Use pd.Timedelta(days=7) for vectorized addition with Series [OK]
Hint: Use pd.Timedelta(days=7) for vectorized addition with Series [OK]
Common Mistakes:
  • Passing integer without units
  • Multiplying Timedelta by length of DataFrame
  • Not using vectorized Timedelta correctly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard