Calculate Date Difference

PythonPythonBeginner
Practice Now

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

Introduction

In Python, we can calculate the difference between two dates in days using the datetime module. This challenge will test your ability to write a function that takes two dates as input and returns the number of days between them.


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/date_time("`Date and Time`") subgraph Lab Skills python/comments -.-> lab-13614{{"`Calculate Date Difference`"}} python/tuples -.-> lab-13614{{"`Calculate Date Difference`"}} python/function_definition -.-> lab-13614{{"`Calculate Date Difference`"}} python/importing_modules -.-> lab-13614{{"`Calculate Date Difference`"}} python/using_packages -.-> lab-13614{{"`Calculate Date Difference`"}} python/standard_libraries -.-> lab-13614{{"`Calculate Date Difference`"}} python/date_time -.-> lab-13614{{"`Calculate Date Difference`"}} end

Date Difference in Days

Write a function days_diff(start, end) that takes two date objects as input and returns the number of days between them. The function should subtract start from end and use datetime.timedelta.days to get the day difference.

def days_diff(start, end):
  return (end - start).days
from datetime import date

days_diff(date(2020, 10, 25), date(2020, 10, 28)) ## 3

Summary

In this challenge, you learned how to calculate the difference between two dates in days using the datetime module in Python. You also practiced writing a function that takes two dates as input and returns the number of days between them.

Other Python Tutorials you may like