Challenge - 5 Problems
Date Arithmetic Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Try adding a timedelta object directly to a pandas Series of datetime values.
✗ Incorrect
Adding a timedelta object to a pandas Series of datetime values adds the time delta to each element. The output shows the dates shifted by 3 days with time included as 00:00:00.
❓ data_output
intermediate2: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'])
Attempts:
2 left
💡 Hint
Subtracting timedelta decreases the datetime values by the specified duration.
✗ Incorrect
Subtracting 5 hours from each timestamp shifts the time earlier by 5 hours.
🔧 Debug
advanced2: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)
Attempts:
2 left
💡 Hint
Check the data type of the 'date' column before adding timedelta.
✗ Incorrect
The 'date' column contains strings, not datetime objects. Adding timedelta to strings causes a TypeError.
🚀 Application
advanced2: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']) })
Attempts:
2 left
💡 Hint
Subtracting datetime columns gives a timedelta Series; use .dt.days to get integer days.
✗ Incorrect
Subtracting two datetime columns returns a timedelta Series. Using .dt.days extracts the number of days as integers.
🧠 Conceptual
expert2: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?
Attempts:
2 left
💡 Hint
Timedelta represents a fixed duration, not calendar-aware shifts.
✗ Incorrect
Timedelta adds a fixed duration (e.g., 24 hours) to timestamps, ignoring daylight saving time shifts.