Skip to content

Latest commit

 

History

History
54 lines (32 loc) · 2.12 KB

Python_Convert_relative_time_delta_to_months.md

File metadata and controls

54 lines (32 loc) · 2.12 KB



Template request | Bug report | Generate Data Product

Tags: #python #datetime #relativedelta #calculate #date #time #dateutil

Author: Florent Ravenel

Description: This notebook is designed to convert the relative time delta between two dates into months. By utilizing the relativedelta function, the conversion becomes more accurate compared to using timedelta, as relativedelta considers the varying number of days in each month.

References:

Input

Import libraries

from datetime import datetime
from dateutil.relativedelta import relativedelta

Setup Variables

  • start_date: First date
  • end_date: Second date
start_date = datetime(2022, 1, 15)
end_date = datetime(2023, 5, 22)

Model

Calculate delta and convert to months

Calculate the time delta between two dates using the relativedelta function from the dateutil library.

delta = relativedelta(end_date, start_date)
months = round(delta.days / 30 + delta.months + 12 * delta.years, 1)

Output

Display result

print(f"The time delta is {months} months.")