Calculate Days from Today

PythonPythonBeginner
Practice Now

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

Introduction

In Python, you can easily calculate the date of n days from today using the datetime module. In this challenge, you will be asked to write a function that takes an integer n as input and returns the date of n days from today.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) 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-13615{{"Calculate Days from Today"}} python/tuples -.-> lab-13615{{"Calculate Days from Today"}} python/function_definition -.-> lab-13615{{"Calculate Days from Today"}} python/importing_modules -.-> lab-13615{{"Calculate Days from Today"}} python/using_packages -.-> lab-13615{{"Calculate Days from Today"}} python/standard_libraries -.-> lab-13615{{"Calculate Days from Today"}} python/date_time -.-> lab-13615{{"Calculate Days from Today"}} end

Days from now

Write a function days_from_now(n) that takes an integer n as input and returns the date of n days from today.

To solve this problem, you can follow these steps:

  1. Import the datetime module.
  2. Use the date.today() method to get the current date.
  3. Use the timedelta method to add n days to the current date.
  4. Return the new date.
from datetime import timedelta, date

def days_from_now(n):
  return date.today() + timedelta(n)
days_from_now(5) ## date(2020, 11, 02)

Summary

In this challenge, you learned how to calculate the date of n days from today using the datetime module in Python. You can use this function to perform various date calculations in your Python programs.