Erica
Erica

Reputation: 61

Calculating end date of a loan in Python 3

I am working on a project for a class for which (among other things) I need to calculate the end date of a loan given the first payment date, the loan term in years, and the number of payments per year. So for example, if the first payment date is 1/1/2018 and there are 12 payment periods per year for a rate of two years, the loan end date will be 12/1/2019. I need to be able to calculate this for essentially any integers that the user inputs. The payment periods can be 4 for quarterly, etc.

So far, I have started by taking the date string entered (which is in the format DD/MM/YYYY) and splitting it with "/" being the delimiter. I then convert each part to an integer.

From here I am not sure how to proceed. I am very limited in my knowledge of Python so far (we just started decision structures), so I am assuming a for loop would be easiest to grasp for me. I'm not sure how I'd even start something like that. Can anyone at least help point me in the right direction?

Code below.

first_date=input("Please enter the first payment date (DD/MM/YYYY):")

first_date.split("/")
month,day,year=first_date.split("/")
month=int(month)
day=int(day)
year=int(year)

Upvotes: 2

Views: 1134

Answers (1)

heemayl
heemayl

Reputation: 42087

You should deal with this using datetime operations and operators, not by text-processing. You can use datetime, time and similar modules.

Here is an example workflow:

In [40]: import datetime

# Input string
In [41]: first_date_str = '31/12/2018'

# Converting the input to a datetime object
In [42]: first_date_dt = datetime.datetime.strptime(first_date_str, '%d/%m/%Y')

# Let's check
In [43]: first_date_dt
Out[43]: datetime.datetime(2018, 12, 31, 0, 0)

# Adding 180 days
In [44]: first_date_dt + datetime.timedelta(days=180)
Out[44]: datetime.datetime(2019, 6, 29, 0, 0)

In [45]: last_date_dt = first_date_dt + datetime.timedelta(days=180)

# Converting datetime object back to string
In [46]: datetime.datetime.strftime(last_date_dt, '%d/%m/%Y')
Out[46]: '29/06/2019'

Hope this will get you started.

Upvotes: 3

Related Questions