How to add days to a given date in Python
How to add days to a given date in Python.
Here's a detailed step-by-step tutorial on how to add days to a given date in Python. We will cover different methods to achieve this:
Method 1: Using the datetime module
- Import the
datetimemodule by adding the following line at the top of your Python script:
import datetime
- Create a
datetimeobject representing the given date. You can do this by calling thedatetime.datetimeclass and passing the year, month, and day as arguments. For example, to represent the date January 1, 2022, you would use:
given_date = datetime.datetime(2022, 1, 1)
- Define the number of days you want to add to the given date. For example, if you want to add 7 days, you would use:
num_days = 7
- Use the
timedeltafunction from thedatetimemodule to add the specified number of days to the given date. Thetimedeltafunction takes the number of days as an argument and returns atimedeltaobject. You can add thistimedeltaobject to the given date using the+operator. For example, to add 7 days to the given date, you would use:
new_date = given_date + datetime.timedelta(days=num_days)
- The variable
new_datenow holds the updated date after adding the specified number of days to the given date. You can print it to verify the result:
print(new_date)
Here's the complete code:
import datetime
given_date = datetime.datetime(2022, 1, 1)
num_days = 7
new_date = given_date + datetime.timedelta(days=num_days)
print(new_date)
Method 2: Using the dateutil module
- Install the
dateutilmodule if you haven't already. You can do this by running the following command in your terminal:
pip install python-dateutil
- Import the
dateutilmodule by adding the following line at the top of your Python script:
from dateutil.relativedelta import relativedelta
Create a
datetimeobject representing the given date. You can do this using thedatetime.datetimeclass, similar to Method 1.Define the number of days you want to add to the given date, similar to Method 1.
Use the
relativedeltafunction from thedateutilmodule to add the specified number of days to the given date. Therelativedeltafunction takes the number of days as an argument and returns arelativedeltaobject. You can add thisrelativedeltaobject to the given date using the+operator, similar to Method 1.The variable
new_datenow holds the updated date after adding the specified number of days to the given date. You can print it to verify the result, similar to Method 1.
Here's the complete code:
from dateutil.relativedelta import relativedelta
given_date = datetime.datetime(2022, 1, 1)
num_days = 7
new_date = given_date + relativedelta(days=num_days)
print(new_date)
That's it! You now know how to add days to a given date in Python using two different methods. Choose the one that suits your needs best.