In this Python program example, we are going to learn how to add and substract days time to a date in Python. We will use timedelta module of Python which is used to manipulate the datetime object in Python.
How do you add days to Date in Python
from datetime import datetime,timedelta
currentTimeDate = datetime.now()
AddedTimeDate = datetime.now() + timedelta(5)
currentTime = currentTimeDate.strftime('%Y-%m-%d')
print("Today's DateTime=",currentTime)
AddedTime = AddedTimeDate.strftime('%Y-%m-%d')
print("DateTime after adding 5 days=",AddedTime)
Output:
Today’s DateTime= 2023-02-18
DateTime after adding 5 days= 2023-02-23
How do you substract days to Date in Python
from datetime import datetime,timedelta
currentTimeDate = datetime.now()
AddedTimeDate = datetime.now() - timedelta(5)
currentTime = currentTimeDate.strftime('%Y-%m-%d')
print("Today's DateTime=",currentTime)
AddedTime = AddedTimeDate.strftime('%Y-%m-%d')
print("DateTime after Substracting 5 days=",AddedTime)
Output:
Today’s DateTime= 2023-02-18
DateTime after Substracting 5 days= 2023-02-13
Source Code Explanation
- Import datetime & timedelta from datetime module.
- Create a “currentTimedate” variable and save current date and add 5 days in this variable by timedelta method.
- Then change the value of currentTimedate in string by using strftime method and save it in currentTime variable.
- Then used print command to get output of code.