📖 Scenario: Imagine you work in a library. You have a list of books with their borrow dates. You want to find out when each book should be returned by adding a fixed borrowing period.
🎯 Goal: You will create a dictionary of books with their borrow dates, set a borrowing period, calculate the return dates by adding the borrowing period to each borrow date, and finally display the return dates.
📋 What You'll Learn
Create a dictionary with book titles as keys and borrow dates as datetime objects as values
Create a variable for the borrowing period using timedelta
Calculate return dates by adding the borrowing period to each borrow date using a dictionary comprehension
Print the dictionary of return dates
💡 Why This Matters
🌍 Real World
Libraries, rental services, and any system that tracks borrowed items use date arithmetic to calculate due dates.
💼 Career
Understanding date arithmetic is important for data analysts and scientists working with time series data, scheduling, and event tracking.
Progress0 / 4 steps
1
Create the dictionary of borrow dates
Create a dictionary called borrow_dates with these exact entries: 'Book A': datetime(2024, 6, 1), 'Book B': datetime(2024, 6, 3), 'Book C': datetime(2024, 6, 5). Import datetime from the datetime module.
Data Analysis Python
Hint
Use datetime(2024, 6, 1) to create the date for June 1, 2024.
2
Set the borrowing period
Import timedelta from the datetime module and create a variable called borrow_period that represents 14 days.
Data Analysis Python
Hint
Use timedelta(days=14) to represent 14 days.
3
Calculate return dates using dictionary comprehension
Create a new dictionary called return_dates using a dictionary comprehension. For each book and borrow_date in borrow_dates.items(), add borrow_period to borrow_date.
Data Analysis Python
Hint
Use {book: borrow_date + borrow_period for book, borrow_date in borrow_dates.items()} to create the new dictionary.
4
Print the return dates
Print the return_dates dictionary to see the calculated return dates.
Data Analysis Python
Hint
Use print(return_dates) to display the dictionary.
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
Step 1: Understand the purpose of timedelta
The timedelta object is used to represent a span of time, such as days, seconds, or microseconds.
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.
Final Answer:
A duration or difference between two dates or times -> Option D
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
Step 1: Recall timedelta constructor syntax
The timedelta constructor accepts keyword arguments like days, seconds, etc.
The timedelta constructor requires keyword arguments like days=7; day=7 is invalid keyword causing TypeError.
Step 2: Verify other parts of code
Adding timedelta to datetime is valid, print syntax is correct, and time parameters are optional.
Final Answer:
timedelta uses invalid keyword 'day' -> Option A
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
Step 1: Understand pandas datetime addition
When adding time to pandas datetime columns, use pd.Timedelta for vectorized operations.