0
0
Data Analysis Pythondata~20 mins

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

Choose your learning style9 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.