Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to add Days to a Date in Python?
Next article icon

How to add and subtract days using DateTime in Python?

Last Updated : 10 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

As we know date and time are used in programs where we have to keep track of date and time, so it is necessary to have a module to manipulate date and time. In Python, a DateTime module deals with dates and times. Datetime module is built into Python standard library.

Datetime module consists of the following classes:

 

Name

Description

1.dateIt shows the date according to the Georgian calendar with attributes are year, month and day.
2.timeIt shows time, independent of any particular day with attributes are hour, minute, second, microsecond, and tzinfo.
3.DateTimeIt is a collection of Dates and Times with the attributes year, month, day, hour, minute, second, microsecond, and tzinfo.
4.timedeltaIt is used to manipulate Date.
5.tzinfoIt provides information about the Time zone.

Add and subtract days using DateTime in Python

For adding or subtracting Date, we use something called timedelta() function which can be found under the DateTime class. It is used to manipulate Date, and we can perform arithmetic operations on dates like adding or subtracting. timedelta is very easy and useful to implement.

Syntax of DateTime 

Syntax: class datetime.timedelta(days=10, seconds=40, microseconds=10, milliseconds=60, minutes=10, hours=4, weeks=8)

Returns : Date

Note : if we doesn’t specify by default it takes integer as an day. 

Example 1. Add days from a Current date

We have created a variable called current_date which holds the current date, and then prints that current date. After that, I used timedelta function and in the parameter, We have passed a value that how many days want to add (This value can be any integer).

Python3

from datetime import datetime, timedelta
print("Current time: ", datetime.now())
print(datetime.now() + timedelta(days=5, hours=-5))
                      
                       

Output:  

Current time:  2022-07-13 10:02:04.394152 2022-07-18 05:02:04.394152

Example 2. Subtract days from a Current date

As in the above code, I have created a variable called current_date which holds the current date, and then prints that current date. After that, I used timedelta function and in the parameter, We have passed a value that how many days want to subtract (This value can be any integer).

Python3

from datetime import datetime, timedelta
print("Current time: ", datetime.now())
print(datetime.now() - timedelta(days=5, hours=-5))
                      
                       

 Output: 

Current time:  2022-07-13 10:10:27.980591 2022-07-08 15:10:27.981589

Example 3: Subtract months from a Current date

In this example, we have created a self-defined date-time and subtracted 4 months from the current time to get the date-time of the last 4 months ago.

Python3

import datetime     
from dateutil.relativedelta import relativedelta  
 
print("Current Date time: ", datetime.datetime(2022, 8, 13, 10, 53, 10) ) 
 
new_months = my_datetime - relativedelta(months = 4)
 
print("X Month ago: ", new_months)
                      
                       

 Output:  

Current Date time:  2022-08-13 10:53:10 X Month ago:  2022-02-20 07:35:18

Example 4: Add years from a Current date

In this example, we have created a self-defined date-time and added 5 years from the current time to get the date-time after 5 years.

Python3

import datetime     
from dateutil.relativedelta import relativedelta  
 
print("Current Date time: ", datetime.datetime(2022, 8, 13, 10, 53, 10) ) 
 
Year = my_datetime + relativedelta(years = 5)
 
print("After X Year: ", Year)
                      
                       

Output: 

Current Date time:  2022-08-13 10:53:10 After X Year:  2027-06-20 07:35:18


Next Article
How to add Days to a Date in Python?

A

amnindersingh1414
Improve
Article Tags :
  • Python
  • Python datetime-program
  • Python-datetime
Practice Tags :
  • python

Similar Reads

  • How to add Days to a Date in Python?
    Python provides an in-built module datetime which allows easy manipulation and modification of date and time values. It allows arithmetic operations as well as formatting the output obtained from the DateTime module. The module contains various classes like date, time, timedelta, etc. that simulate
    2 min read
  • How to Add and Subtract Days to and from Date in R?
    Managing dates and times is a crucial aspect of data analysis, and R provides robust facilities for dealing with date objects. In this post, we will look at how to add and remove days from a date in R. Whether you're dealing with time series data, need to compute future dates, or want to browse thro
    4 min read
  • Date Calculator for adding and subtracting days Using Tkinter - Python
    Prerequisite: Tkinter, tkcalendar in Tkinter, and DateTime Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkin
    3 min read
  • How to Format date using strftime() in Python ?
    In this article, we will see how to format date using strftime() in Python. localtime() and gmtime() returns a tuple representing a time and this tuple is converted into a string as specified by the format argument using python time method strftime(). Syntax: time.strftime(format[, sec]) sec: This i
    2 min read
  • How to Add or subtract time span to a datetime in R ?
    The time objects in R can be declared either using POSIXct class, which offers fast manipulation and storage of such objects. External packages in R also help in working with time and dates and allow both comparison and direct arithmetic operations to be performed upon them. In this article, we are
    4 min read
  • How to Add or Subtract Dates in Excel
    New to Excel and seeking a way to add or subtract dates, then this guide on how to add or subtract dates in Excel will expalin you the right way to manage project timelines, schedules, or due dates. We’ll break down simple steps to add or subtract dates using easy formulas and time-saving tips. How
    5 min read
  • How to Convert DateTime to UNIX Timestamp in Python ?
    The Unix timestamp is a single signed integer that grows by one every second, allowing computers to store and manipulate conventional date systems. The software is then translated into a human-readable format. The Unix timestamp is the number of seconds calculated since January 1, 1970. In this arti
    5 min read
  • Addition and Subtraction on TimeDelta objects using Pandas - Python
    TimeDelta module is used to represent the time in the pandas module and can be used in various ways. Performing operations like addition and subtraction are very important for every language but performing these tasks on dates and time can be very valuable. Operations on TimeDelta dataframe or serie
    2 min read
  • How to Get Current Date and Time using Python
    In this article, we will cover different methods for getting data and time using the DateTime module and time module in Python. Different ways to get Current Date and Time using PythonCurrent time using DateTime objectGet time using the time moduleGet Current Date and Time Using the Datetime ModuleI
    6 min read
  • How to convert datetime to date in Python
    In this article, we are going to see how to convert DateTime to date in Python. For this, we will use the strptime() method and Pandas module. This method is used to create a DateTime object from a string. Then we will extract the date from the DateTime object using the date() function and dt.date f
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences