Thursday, July 9, 2020

Python: How to calculate number of Whole Months between Two Dates

I was building an application in Python for automating some routine office work. Doing which, I came across a problem where I have to calculate the extra deduction from the salary of employee if s/he is not present in the office even for a single day of any month. So, let's break down the problem in smaller chunks and solve it.

Simplified version of our task

  • Get the two dates from user
  • First input will be starting date (inclusive)
  • Second input will be ending date (inclusive)
  • Convert the raw input into a date object of Python
  • Pass it to a function for result (whole months) calculation
  • Print the result.

Converting raw input of date into date object

In Python, all the user input from input function is receive as a string of text. We can process that string of text and extract the exact day, month and year values if user follows given standard format of input. This is demonstrated below.
from datetime import date
rawDIn = input("Enter a date (MM/DD/YYYY) :")
imonth, idate, iyear = map(int, rawDIn.split('/'))
dateObj = date(iyear, imonth, idate)
Split method will return three strings containing month, date and year which will mapped to imonth, idate and iyear as an integer.

Checking for leap year to fix days in Feb

For checking if a given year is leap year or not, there is build-in function in python, however, i build my own which returns True if given year is leap and False if it is not.
def isleapyear(year):
__if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
____return True
__else:
____return False

Function for checking whole months between two dates

Below is the final code embedded from my GitHub repository which will take two param being startdate and enddate and print the whole months between those two dates and finally returns the number of whole months.

No comments :

Post a Comment