How to add days to date in Python
Today we are going to learn how to add days to date in Python. In my previous few tutorials, have shown you working with datetime in Python.
Here are some links to my previous posts:
So this time I will focus on Adding days to date.
- Add days to a specific date
- Add days to the current date
Add days to date in Python
In order to add days to a specific date we will have to use the below module:
- datetime module
In this module, there are many useful classes to manipulate date and time. We will use the following classes here:
Python program to add days to date
from datetime import datetime, timedelta specific_date = datetime(2019, 3, 5) new_date = specific_date + timedelta(21) print (new_date)
$ python codespeedy.py 2019-03-26 00:00:00
We can also use timedelta(days=21) instead of timedelta(21), both will give you the same result.
new_date = specific_date + timedelta(21)
The above line is used to add 21 number of days to the specified date.
in datetime() we have passed a specific date as a parameter.
Then we have done the addition of days to date using the “+” operator.
Add any number of days to current date
To get the current date time we can use the below code:
current_date = datetime.today()
Or we can also use the below one:
current_date = datetime.now()
datetime.now() and datetime.today() both will return the current date and time.
So here is the Python code:
from datetime import datetime, timedelta print(datetime.today()) #print today's date time new_date = datetime.today() + timedelta(12) print (new_date) #print new date time after addition of days to the current date
$ python codespeedy.py 2019-04-08 20:59:26.580545 2019-04-20 20:59:26.581544
You may also learn,