Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
1.1k views
in Python by (176k points)
How do I add or subtract days, weeks, or months to a date in Python?

Please log in or register to answer this question.

1 Answer

0 votes
by (176k points)

To add or subtract days, weeks, or months to a date in Python, you can use the built-in datetime module.

Here's an example of how to add or subtract days, weeks, or months to a date in Python:

import datetime

# Create a date object
date = datetime.date(2023, 3, 28)

# Add or subtract days to the date
new_date = date + datetime.timedelta(days=7)  # Add 7 days
new_date = date - datetime.timedelta(days=7)  # Subtract 7 days

# Add or subtract weeks to the date
new_date = date + datetime.timedelta(weeks=2)  # Add 2 weeks
new_date = date - datetime.timedelta(weeks=2)  # Subtract 2 weeks

# Add or subtract months to the date
new_date = date + datetime.timedelta(days=30)  # Add 1 month (assuming 30 days in a month)
new_date = date - datetime.timedelta(days=30)  # Subtract 1 month (assuming 30 days in a month)
 

In the example above, datetime.date(2023, 3, 28) creates a date object representing March 28th, 2023.

To add or subtract a specific amount of time to the date, you can use the timedelta function of the datetime module. The timedelta function takes arguments for the number of days, weeks, and/or months to add or subtract from the date.

Once you have created a timedelta object, you can add or subtract it from the original date to get a new date.

Related questions

0 votes
1 answer
asked Mar 28, 2023 in Python by kvdevika (176k points)
+1 vote
1 answer
asked Mar 28, 2023 in Python by kvdevika (176k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...