Core Python / Date Time Exercise Answers

Core Python / Date Time Exercise Answers#

 1# 1. Parse date
 2
 3import datetime
 4
 5def parse_date(date_str):
 6    """
 7    Parse a date string in the format "YYYY-MM-DD" and return the corresponding datetime.date object.
 8    
 9    Parameters:
10        date_str (str): Date string in the format "YYYY-MM-DD".
11        
12    Returns:
13        datetime.date: Corresponding date object.
14        
15    Raises:
16           ValueError: invalid date format
17    """
18
19    year, month, day = map(int, date_str.split('-'))
20    return datetime.date(year, month, day)
21
22# Example usage:
23date_string = "2024-06-02"
24date_object = parse_date(date_string)
25print("Parsed date object:", date_object)
26
27try:
28    parse_date("2024-02-30")
29except ValueError:
30    print("Invalid date string. Please use the format 'YYYY-MM-DD'.")
Parsed date object: 2024-06-02
Invalid date string. Please use the format 'YYYY-MM-DD'.
 1# 2.Calculate Business Days
 2import datetime
 3
 4def count_business_days(start_date, end_date):
 5    """
 6    Calculate the number of business days (excluding weekends) between two given dates.
 7    
 8    Parameters:
 9        start_date (datetime.date): The start date.
10        end_date (datetime.date): The end date.
11        
12    Returns:
13        int: The number of business days between start_date and end_date (inclusive).
14    """
15    # Initialize counters
16    business_days = 0
17    current_date = start_date
18
19    # Iterate through each date between start_date and end_date
20    while current_date <= end_date:
21        # Check if the current day is a weekday (Monday=0, Sunday=6)
22        if current_date.weekday() < 5:
23            business_days += 1
24        # Move to the next day
25        current_date += datetime.timedelta(days=1)
26
27    return business_days
28
29# Example usage:
30start_date = datetime.date(2024, 6, 1)
31end_date = datetime.date(2024, 6, 15)
32print("Number of business days:", count_business_days(start_date, end_date))
Number of business days: 10
 1# 3. Calculate the Number of Years until Retirement
 2import datetime
 3
 4def calculate_years_until_retirement(date_of_birth, retirement_age=67):
 5    """
 6    Calculate the number of years until retirement based on the date of birth and retirement age.
 7    
 8    Parameters:
 9        date_of_birth (datetime.date): Date of birth.
10        retirement_age (int): Retirement age. Default is 67.
11        
12    Returns:
13        int: Number of years until retirement.
14    """
15    # Get the current date
16    current_date = datetime.date.today()
17    
18    # Calculate the age of the user
19    age = current_date.year - date_of_birth.year - ((current_date.month, current_date.day) < (date_of_birth.month, date_of_birth.day))
20    
21    # Calculate years until retirement
22    years_until_retirement = max(0, retirement_age - age)
23    
24    return years_until_retirement
25
26def get_date_input(prompt):
27    """
28    Prompt the user to enter a date in the format "YYYY-MM-DD" and return the corresponding date object.
29    
30    Parameters:
31        prompt (str): The prompt message to display.
32        
33    Returns:
34        datetime.date: Date object entered by the user.
35    """
36    while True:
37        date_str = input(prompt)
38        try:
39            # Parse the date string
40            date_obj = datetime.datetime.strptime(date_str, "%Y-%m-%d").date()
41            return date_obj
42        except ValueError:
43            print("Invalid date format. Please enter the date in the format 'YYYY-MM-DD'.")
44
45# Prompt the user to enter their date of birth
46print("Please enter your date of birth:")
47dob = get_date_input("Date of Birth (YYYY-MM-DD): ")
48
49# Calculate the years until retirement
50years_until_retirement = calculate_years_until_retirement(dob)
51
52# Display the result
53print(f"You have {years_until_retirement} years until retirement.")
Please enter your date of birth:
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
Cell In[3], line 47
     45 # Prompt the user to enter their date of birth
     46 print("Please enter your date of birth:")
---> 47 dob = get_date_input("Date of Birth (YYYY-MM-DD): ")
     49 # Calculate the years until retirement
     50 years_until_retirement = calculate_years_until_retirement(dob)

Cell In[3], line 37, in get_date_input(prompt)
     27 """
     28 Prompt the user to enter a date in the format "YYYY-MM-DD" and return the corresponding date object.
     29 
   (...)
     34     datetime.date: Date object entered by the user.
     35 """
     36 while True:
---> 37     date_str = input(prompt)
     38     try:
     39         # Parse the date string
     40         date_obj = datetime.datetime.strptime(date_str, "%Y-%m-%d").date()

File ~/Documents/GitHub/jupyternotebooks/venv/lib/python3.12/site-packages/ipykernel/kernelbase.py:1281, in Kernel.raw_input(self, prompt)
   1279 if not self._allow_stdin:
   1280     msg = "raw_input was called, but this frontend does not support input requests."
-> 1281     raise StdinNotImplementedError(msg)
   1282 return self._input_request(
   1283     str(prompt),
   1284     self._parent_ident["shell"],
   1285     self.get_parent("shell"),
   1286     password=False,
   1287 )

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.
 1# 4. Determine the Time Remaining until Bond Maturity
 2import datetime
 3
 4def remaining_time_to_maturity(issue_date, maturity_date):
 5    """
 6    Calculate the time remaining until maturity based on the issue date and maturity date of a bond.
 7    
 8    Parameters:
 9        issue_date (datetime.date): The issue date of the bond.
10        maturity_date (datetime.date): The maturity date of the bond.
11        
12    Returns:
13        tuple: A tuple containing two values:
14            - Percentage of time passed for maturity
15            - Number of years remaining until maturity
16    """
17    # Get the current date
18    current_date = datetime.date.today()
19    
20    # Calculate the total time to maturity
21    total_time_to_maturity = (maturity_date - issue_date).days
22    
23    # Calculate the time passed since issuance
24    time_passed = (current_date - issue_date).days
25    
26    # Calculate the percentage of time passed for maturity
27    percentage_time_passed = (time_passed / total_time_to_maturity) * 100
28    
29    # Calculate the number of years remaining until maturity
30    years_remaining = (maturity_date - current_date).days / 365.25
31    
32    return percentage_time_passed, years_remaining
33
34# Example usage:
35issue_date = datetime.date(2020, 1, 1)
36maturity_date = datetime.date(2030, 1, 1)
37
38percentage_passed, years_remaining = remaining_time_to_maturity(issue_date, maturity_date)
39print("Percentage of time passed for maturity:", percentage_passed)
40print("Number of years remaining until maturity:", years_remaining)
Percentage of time passed for maturity: 44.2102381604161
Number of years remaining until maturity: 5.579739904175223