Compute Time Period#

The compute_time_period function calculates the time difference between two datetime objects in years, months, and days. It is useful for finding the duration between two dates or timestamps.

compute_time_period() function#

Function#

def compute_time_period(timestamp_1, timestamp_2):
    """
    Function to compute the time difference between two timestamps in years, months, and days.

    Parameters
    ----------
    timestamp_1 : datetime.datetime
        The first timestamp.
    timestamp_2 : datetime.datetime
        The second timestamp.

    Returns
    -------
    str
        A string representing the time difference in years, months, and days.
    """

    # Calculate the difference in years, months, and days
    year = timestamp_1.year - timestamp_2.year
    month = timestamp_1.month - timestamp_2.month
    day = timestamp_1.day - timestamp_2.day

    # If the month difference is negative, adjust the year and month
    if month < 0:
        year = year - 1
        month = 12 + month

    # If the day difference is negative, adjust the day
    if day < 0:
        day = -day

    # Return a string representation of the time difference in years, months, and days
    return f'{year} Years {month} Months {day} Days'

Description#

The compute_time_period function computes the time difference between two datetime objects in years, months, and days. It takes two datetime objects as input and returns a string representing the time difference.

Parameters#

  • timestamp_1 (datetime.datetime): The first timestamp.

  • timestamp_2 (datetime.datetime): The second timestamp.

Returns#

  • str: A string representing the time difference in years, months, and days.

import ds4finance as dsf
import datetime

timestamp_1 = datetime.datetime(2023, 4, 21)
timestamp_2 = datetime.datetime(2015, 12, 31)

time_difference = dsf.compute_time_period(timestamp_1, timestamp_2)
time_difference
'7 Years 4 Months 10 Days'

In this example, we use the compute_time_period function to calculate the time difference between two datetime objects, timestamp_1 and timestamp_2. The function returns the time difference as a string: “7 Years 3 Months 21 Days”.