Calculate Month Difference in Python

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, you can calculate the difference between two dates using the datetime module. This challenge will test your ability to calculate the month difference between two dates.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") python/PythonStandardLibraryGroup -.-> python/date_time("`Date and Time`") subgraph Lab Skills python/comments -.-> lab-13696{{"`Calculate Month Difference in Python`"}} python/tuples -.-> lab-13696{{"`Calculate Month Difference in Python`"}} python/function_definition -.-> lab-13696{{"`Calculate Month Difference in Python`"}} python/importing_modules -.-> lab-13696{{"`Calculate Month Difference in Python`"}} python/using_packages -.-> lab-13696{{"`Calculate Month Difference in Python`"}} python/standard_libraries -.-> lab-13696{{"`Calculate Month Difference in Python`"}} python/math_random -.-> lab-13696{{"`Calculate Month Difference in Python`"}} python/date_time -.-> lab-13696{{"`Calculate Month Difference in Python`"}} end

Date Difference

Write a function called months_diff(start, end) that takes in two date objects and returns the month difference between them. The function should:

  1. Subtract start from end and use datetime.timedelta.days to get the day difference.
  2. Divide by 30 and use math.ceil() to get the difference in months (rounded up).
from math import ceil

def months_diff(start, end):
  return ceil((end - start).days / 30)
from datetime import date

months_diff(date(2020, 10, 28), date(2020, 11, 25)) ## 1

Summary

In this challenge, you learned how to calculate the month difference between two dates in Python. Remember to use the datetime module to subtract the dates and math.ceil() to round up the result. Good luck!

Other Python Tutorials you may like