How to Add and Subtract Days Using DateTime in Python?5 Jan 2025 | 4 min read Python provides many modules and classes for modifying the data, like adding or subtracting days. One such module is the datetime module. DatetimeThe datetime module in Python is a powerful tool that provides several classes for working with dates and times. With this module, you can efficiently manipulate and represent dates and times in various formats. It consists of various classes, including the datetime and timedelta classes, designed to simplify your work. What is the datetime Class?The datetime class is the most commonly used, representing a point in time that includes both date and time components. It has several attributes, such as year, month, day, hour, minute, second, and microsecond, making it easy to work with. What is the timedelta Class?The datetime module in Python provides the timedelta class that represents a time duration, which is nothing but the difference between two dates or times. This class allows you to perform arithmetic operations on the dates and times, making it easy to add or subtract a certain amount of time from a given date or time. The timedelta class is particularly useful when you need to perform calculations such as finding the difference between two dates and adding or subtracting days, hours, minutes, or seconds from a given date or time. ![]() 1. Adding and Subtracting Days from the Current DateExample 1 Let us see how we can create a date using the datetime class and modify it. Program Output: 2024-01-01 17:20:26.097500 Current date and time: 2024-01-01 17:20:26.097500 Date after adding 3 days: 2024-01-04 17:20:26.097500 Explanation We have originated the current date using timedate class and modified the date using timedelta class. Example 2:Here is an example program to subtract the days from the date: Program Output: 2024-01-01 17:39:24.179001 Current date and time: 2024-01-01 17:39:24.179001 Date after subtracting 3 days: 2023-12-29 17:39:24.179001 Explanation Here, we have subtracted 3 days from the current date using the timedelta class. Adding and Subtracting Days from the Specified DateExample 1:Here is an example program to add days to the specified date: Program Output: Specified Date time: 2023-09-12 10:13:10 Current date 2023-09-12 10:13:10 New date after adding 7 days: 2023-09-19 10:13:10 New date after subtracting 7 days: 2023-09-05 10:13:10 Explanation We imported the required libraries, specified the datetime object, created it using the datetime class, and manipulated it using the timedelta class. Here, we have added and subtracted the days from it. At last, we printed the modified dates. User Input and Dynamic ManipulationLet us consider a simple program to get the date and number of days from the user for the modification Program Output: Enter a date (YYYY-MM-DD): 2023-12-31 Enter the number of days to add/subtract: 9 Result after adding: 2024-01-09 00:00:00 Result after subtracting: 2023-12-22 00:00:00 Explanation We begin by importing the necessary modules and creating a datetime object called current_datetime that represents September 12, 2023, at 10:13:10. Next, we perform two operations on the current_datetime: 1. Adding 7 days (timedelta(days=7)): We use the timedelta class to represent 7 days. By adding this duration to current_datetime, we obtain a new date called new_date_afteraddition. 2. Subtracting 7 days (timedelta(days=-7)): We use the timedelta class again, but with a negative value for the days parameter. By subtracting this duration from current_datetime, we obtain a new date called new_date_aftersubtraction. Finally, we print the results of the operations. This section displays the original current_datetime, the new date after adding 7 days (new_date_afteraddition), and the new date after subtracting 7 days (new_date_aftersubtraction). ConclusionUtilizing Python's `datetime` module is a reliable and straightforward way to add or subtract days from dates. With the `timedelta` class of the module, you can easily manipulate time intervals and add or subtract days to and from existing dates with great precision. This functionality is particularly useful in various applications such as date arithmetic, scheduling, and data analysis, where accurate tracking and manipulation of time is crucial. By using the versatile capabilities of the `datetime` module, Python developers can efficiently handle date-related operations, ensuring precision and reliability in their applications. Next TopicHow-to-add-days-to-a-date-in-python |
Files are saved in the .ipynb format in Jupyter Notebook. It's a Markdown, code-filled JSON document with outputs. We would want to convert Jupyter Notebook to ordinary Python script in a number of situations. For instance, you could want to make your notebook an independent...
7 min read
Jupyter Notebook is now a global resource for researchers, builders, and records scientists. It is perfect for records exploration, experimentation, and end result sharing due to its interactive environment, which allows the easy integration of code, visualizations, and explanatory text. But as notebooks end up...
4 min read
Downsampling an image using OpenCV in Python is relatively straightforward. Downsampling refers to reducing the resolution or size of an image. OpenCV is a popular library for image processing in Python. You can use the `cv2.resize()` function to perform downsampling. Here's a simple example: import cv2 #...
20 min read
Building chatbots using Python and Rasa is a popular choice as Rasa is an open-source conversational AI framework that allows you to build natural language understanding (NLU) and dialogue management components for chatbots and virtual assistants. Here's a step-by-step guide on how you can create...
22 min read
A Brief Introduction to Collatz Sequence The Collatz conjecture also called the "3n + 1" conjecture or the Hailstone sequence, is a math problem that has been craving the minds of mathematicians for years. Named after the German mathematician Lothar Collatz, who first introduced it in 1937,...
8 min read
An Introduction to Python for Automotive Development Python is no longer the rigid, and inapplicable programming language it once was, but instead has gained the power to be applied in virtually every form of application, from automobile development to many others. The paper examines the advantages and...
7 min read
The tridiagonal matrix can be explained as a matrix in which all the elements are zero except those on the main diagonal, the diagonal above the main diagonal, and the diagonal below the main diagonal. Example: A = [[1, 4, 0, 0, 0], ...
6 min read
? Introduction: In this tutorial we are learning about how to Add Title to Subplots in Matplotlib. Matplotlib is a widely used Python package for creating plots, subplots, and visualizations with names and descriptions. When creating multiple subimages, it can be helpful to give each subimage a...
5 min read
An Introduction to Tables In data processing and analysis, tables are one of the most effective techniques of presenting data. Ability to handle tabular data, regardless of the size and structure of data that you are working with is significant either if the latter is small...
7 min read
? Introduction From web development to data science, there are a myriad of reasons why people use Python. What is it that makes this language so versatile and dynamic? While developing a program, when dealing with more difficult cases developers must frequently ask themselves if there is...
4 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India