Add or Remove Weeks to & from Date in Python (Example Code)
In this Python tutorial, you’ll learn how to add & subtract weeks to/from a date.
Setting up the Example
Before we can start, we have to load the following modules:
from datetime import datetime, timedelta # Importing modules |
from datetime import datetime, timedelta # Importing modules
The following datetime object below will be used for the examples of this article.
date_x = datetime.today() # Creating example data print(date_x) # 2022-06-10 16:58:14.803875 |
date_x = datetime.today() # Creating example data print(date_x) # 2022-06-10 16:58:14.803875
Example: Remove or Add Certain Number of Days to Date
To add a specific number of weeks to a date, we can use the timedelta function within the weeks parameter:
date_x_weeks_added = date_x + timedelta(weeks = 8) # Add weeks to datetime object print(date_x_weeks_added) # 2022-08-03 16:58:14.803875 |
date_x_weeks_added = date_x + timedelta(weeks = 8) # Add weeks to datetime object print(date_x_weeks_added) # 2022-08-03 16:58:14.803875
A datetime object has been created, which returns our example data 8 weeks in the future.
Similar to add weeks to a date, we can also subtract weeks from a datetime object:
date_x_weeks_subtracted = date_x - timedelta(weeks = 8) # Remove weeks from datetime object print(date_x_weeks_subtracted) # 2022-04-17 16:58:14.803875 |
date_x_weeks_subtracted = date_x - timedelta(weeks = 8) # Remove weeks from datetime object print(date_x_weeks_subtracted) # 2022-04-17 16:58:14.803875
As you can see on the previous python code, we simply have to change the operator from positive to negative.
Note: This article was created in collaboration with Matthias Bäuerlen. Matthias is a programmer who helps to create tutorials on the Python programming language. You might find more info about Matthias and his other articles on his profile page.