Python Date and Time Manipulation

PythonPythonBeginner
Practice Now

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

Introduction

In Python, the datetime module provides classes for working with dates and times. One of the classes in this module is date, which represents a date (year, month, day) and provides various methods to work with dates. Another class is timedelta, which represents a duration or difference between two dates or times.


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-13613{{"`Python Date and Time Manipulation`"}} python/tuples -.-> lab-13613{{"`Python Date and Time Manipulation`"}} python/function_definition -.-> lab-13613{{"`Python Date and Time Manipulation`"}} python/importing_modules -.-> lab-13613{{"`Python Date and Time Manipulation`"}} python/using_packages -.-> lab-13613{{"`Python Date and Time Manipulation`"}} python/standard_libraries -.-> lab-13613{{"`Python Date and Time Manipulation`"}} python/date_time -.-> lab-13613{{"`Python Date and Time Manipulation`"}} end

Days Ago

Your task is to write a function called days_ago(n) that takes an integer n as an argument and returns the date of n days ago from today.

To solve this problem, you need to use the date class from the datetime module to get the current date and the timedelta class to subtract n days from the current date.

from datetime import timedelta, date

def days_ago(n):
  return date.today() - timedelta(n)
days_ago(5) ## date(2020, 10, 23)

Summary

In this challenge, you learned how to use the date and timedelta classes from the datetime module to calculate the date of n days ago from today. This is a useful skill when working with dates and times in Python.

Other Python Tutorials you may like