Date Difference in Days | Challenge

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/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/ErrorandExceptionHandlingGroup(["`Error and Exception Handling`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) 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/ErrorandExceptionHandlingGroup -.-> python/custom_exceptions("`Custom Exceptions`") python/PythonStandardLibraryGroup -.-> python/date_time("`Date and Time`") subgraph Lab Skills python/tuples -.-> lab-13082{{"`Date Difference in Days | Challenge`"}} python/function_definition -.-> lab-13082{{"`Date Difference in Days | Challenge`"}} python/importing_modules -.-> lab-13082{{"`Date Difference in Days | Challenge`"}} python/using_packages -.-> lab-13082{{"`Date Difference in Days | Challenge`"}} python/standard_libraries -.-> lab-13082{{"`Date Difference in Days | Challenge`"}} python/custom_exceptions -.-> lab-13082{{"`Date Difference in Days | Challenge`"}} python/date_time -.-> lab-13082{{"`Date Difference in Days | Challenge`"}} end

Date Difference in Days

Problem

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.

Example

from datetime import date

assert days_diff(date(2020, 10, 25), date(2020, 10, 28)) == 3
assert days_diff(date(2021, 1, 1), date(2021, 1, 1)) == 0
assert days_diff(date(2021, 1, 1), date(2021, 1, 2)) == 1

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