Bird
Raised Fist0
Data Analysis Pythondata~20 mins

Date arithmetic (Timedelta) in Data Analysis Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Timedelta Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Calculate the difference in days between two dates
What is the output of this code snippet that calculates the difference in days between two dates?
Data Analysis Python
import pandas as pd
start_date = pd.to_datetime('2024-01-01')
end_date = pd.to_datetime('2024-01-15')
diff = end_date - start_date
print(diff.days)
A15
B14
C13
DError
Attempts:
2 left
💡 Hint
Remember that the difference between dates counts full days between them.
❓ data_output
intermediate
2:00remaining
Add a timedelta to a date
What is the resulting date after adding 10 days to '2024-03-10'?
Data Analysis Python
import pandas as pd
initial_date = pd.to_datetime('2024-03-10')
new_date = initial_date + pd.Timedelta(days=10)
print(new_date.strftime('%Y-%m-%d'))
A2024-03-20
B2024-03-10
C2024-03-21
D2024-03-19
Attempts:
2 left
💡 Hint
Adding 10 days means moving forward 10 calendar days.
❓ visualization
advanced
3:00remaining
Plotting date ranges with timedelta
Which option correctly creates a plot showing dates from '2024-01-01' to '2024-01-10' with daily intervals?
Data Analysis Python
import pandas as pd
import matplotlib.pyplot as plt
dates = pd.date_range(start='2024-01-01', end='2024-01-10')
values = range(len(dates))
plt.plot(dates, values)
plt.xlabel('Date')
plt.ylabel('Value')
plt.title('Date Range Plot')
plt.show()
AA scatter plot with dates missing Jan 5
BA bar plot with dates on y-axis and values on x-axis
CA line plot with dates on x-axis from Jan 1 to Jan 10 and values 0 to 9 on y-axis
DAn empty plot with no data
Attempts:
2 left
💡 Hint
Check if the dates cover the full range and if the plot type matches the code.
🧠 Conceptual
advanced
2:30remaining
Understanding timedelta components
Given a timedelta of 3 days, 4 hours, and 30 minutes, what is the total number of seconds?
Data Analysis Python
from datetime import timedelta
td = timedelta(days=3, hours=4, minutes=30)
total_seconds = td.total_seconds()
print(int(total_seconds))
A275400
B259200
C302400
D273000
Attempts:
2 left
💡 Hint
Calculate seconds for days, hours, and minutes separately then add.
🔧 Debug
expert
2:00remaining
Identify the error in timedelta subtraction
What error does this code raise when subtracting a timedelta from a string date?
Data Analysis Python
from datetime import timedelta
start = '2024-05-01'
result = start - timedelta(days=5)
print(result)
AAttributeError: 'str' object has no attribute 'days'
BValueError: invalid literal for int() with base 10
CNo error, prints '2024-04-26'
DTypeError: unsupported operand type(s) for -: 'str' and 'datetime.timedelta'
Attempts:
2 left
💡 Hint
Check the data types involved in the subtraction.

Practice

(1/5)
1. What does the timedelta object represent in Python's date arithmetic?
easy
A. A method to convert strings to dates
B. A specific date and time value
C. A function to format dates
D. A duration or difference between two dates or times

Solution

  1. Step 1: Understand the purpose of timedelta

    The timedelta object is used to represent a span of time, such as days, seconds, or microseconds.
  2. Step 2: Differentiate timedelta from other date/time objects

    Unlike a specific date or time, timedelta measures the difference or duration between two dates or times.
  3. Final Answer:

    A duration or difference between two dates or times -> Option D
  4. Quick Check:

    timedelta = duration/difference [OK]
Hint: timedelta means time difference or duration [OK]
Common Mistakes:
  • Confusing timedelta with a specific date
  • Thinking timedelta formats dates
  • Assuming timedelta converts strings
2. Which of the following is the correct way to create a timedelta of 5 days in Python?
easy
A. timedelta(5 days)
B. timedelta(seconds=5)
C. timedelta(days=5)
D. timedelta(day=5)

Solution

  1. Step 1: Recall timedelta constructor syntax

    The timedelta constructor accepts keyword arguments like days, seconds, etc.
  2. Step 2: Identify the correct keyword and format

    timedelta(5 days): syntax error ('days' undefined). timedelta(seconds=5): 5 seconds not days. timedelta(day=5): invalid keyword 'day'. timedelta(days=5): correct days=5.
  3. Final Answer:

    timedelta(days=5) -> Option C
  4. Quick Check:

    Use keyword days=5 for 5 days [OK]
Hint: Use keyword days=number to create timedelta days [OK]
Common Mistakes:
  • Using 'days' without quotes causing NameError
  • Using seconds=5 instead of days=5
  • Misspelling 'days' as 'day'
3. What will be the output of this code?
from datetime import datetime, timedelta
start = datetime(2024, 6, 10)
new_date = start + timedelta(days=7)
print(new_date.strftime('%Y-%m-%d'))
medium
A. 2024-06-17
B. 2024-06-03
C. 2024-07-10
D. 2024-06-10

Solution

  1. Step 1: Understand the initial date

    The variable start is June 10, 2024.
  2. Step 2: Add 7 days using timedelta

    Adding 7 days to June 10 results in June 17, 2024.
  3. Step 3: Format the date output

    The strftime formats the date as 'YYYY-MM-DD', so output is '2024-06-17'.
  4. Final Answer:

    2024-06-17 -> Option A
  5. Quick Check:

    June 10 + 7 days = June 17 [OK]
Hint: Add days to date, then format output string [OK]
Common Mistakes:
  • Subtracting days instead of adding
  • Misreading date format
  • Confusing month and day positions
4. Identify the error in this code snippet:
from datetime import datetime, timedelta
start = datetime(2024, 6, 10)
new_date = start + timedelta(day=7)
print(new_date)
medium
A. timedelta uses invalid keyword 'day'
B. datetime object cannot be added to timedelta
C. print statement syntax is incorrect
D. datetime constructor missing time parameters

Solution

  1. Step 1: Check timedelta constructor usage

    The timedelta constructor requires keyword arguments like days=7; day=7 is invalid keyword causing TypeError.
  2. Step 2: Verify other parts of code

    Adding timedelta to datetime is valid, print syntax is correct, and time parameters are optional.
  3. Final Answer:

    timedelta uses invalid keyword 'day' -> Option A
  4. Quick Check:

    timedelta(days=7) needed, not day=7 [OK]
Hint: Always use keyword days= for timedelta days [OK]
Common Mistakes:
  • Misspelling 'days' as 'day'
  • Thinking datetime + timedelta is invalid
  • Assuming print syntax error
5. You have a DataFrame with a column 'start_date' of type datetime. You want to create a new column 'deadline' that is 10 days after 'start_date'. Which code correctly does this using pandas and timedelta?
import pandas as pd
from datetime import timedelta

df = pd.DataFrame({'start_date': pd.to_datetime(['2024-06-01', '2024-06-05'])})
# Which line correctly adds 10 days?
hard
A. df['deadline'] = df['start_date'] + timedelta(seconds=10)
B. df['deadline'] = df['start_date'] + pd.Timedelta(days=10)
C. df['deadline'] = df['start_date'] + timedelta(day=10)
D. df['deadline'] = df['start_date'] + pd.timedelta(days=10)

Solution

  1. Step 1: Understand pandas datetime addition

    When adding time to pandas datetime columns, use pd.Timedelta for vectorized operations.
  2. Step 2: Check each option

    df['deadline'] = df['start_date'] + pd.Timedelta(days=10): correct pd.Timedelta(days=10). df['deadline'] = df['start_date'] + timedelta(seconds=10): timedelta(seconds=10) adds seconds not days. df['deadline'] = df['start_date'] + timedelta(day=10): invalid keyword day=10. df['deadline'] = df['start_date'] + pd.timedelta(days=10): pd.timedelta doesn't exist.
  3. Final Answer:

    df['deadline'] = df['start_date'] + pd.Timedelta(days=10) -> Option B
  4. Quick Check:

    Use pd.Timedelta for pandas datetime addition [OK]
Hint: Use pd.Timedelta(days=10) to add days to pandas datetime [OK]
Common Mistakes:
  • Using seconds=10 instead of days=10
  • Using invalid keyword 'day=10'
  • Wrong capitalization pd.timedelta
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