Skip to main content

How to subtract days from a given date in Python

How to subtract days from a given date in Python.

Here's a step-by-step tutorial on how to subtract days from a given date in Python:

Step 1: Import the required modules To perform date calculations, we need to import the datetime module from the Python standard library. Open your Python script or interpreter and add the following line at the beginning:

from datetime import datetime, timedelta

Step 2: Get the input date from the user To subtract days from a given date, we need to first obtain the date from the user. You can do this using the input() function and store it in a variable. Here's an example:

input_date = input("Enter a date (YYYY-MM-DD): ")

Step 3: Convert the input date to a datetime object The datetime module provides a strptime() function that allows us to convert a date string to a datetime object. We'll use this function to convert the input date to a datetime object. Here's an example:

date_object = datetime.strptime(input_date, "%Y-%m-%d")

Step 4: Get the number of days to subtract Next, we need to get the number of days to subtract from the user. Again, we can use the input() function to obtain this value and store it in a variable. Here's an example:

days_to_subtract = int(input("Enter the number of days to subtract: "))

Step 5: Subtract days from the date To subtract the specified number of days from the date, we can use the timedelta() function provided by the datetime module. This function takes the number of days as an argument and returns a timedelta object. We'll subtract this timedelta object from our original date to get the new date. Here's an example:

new_date = date_object - timedelta(days=days_to_subtract)

Step 6: Display the result Finally, we can display the new date to the user. We can use the strftime() function to format the datetime object as a string in the desired format. Here's an example:

formatted_date = new_date.strftime("%Y-%m-%d")
print("The new date is:", formatted_date)

And that's it! You have successfully subtracted days from a given date in Python. Here's the complete code:

from datetime import datetime, timedelta

input_date = input("Enter a date (YYYY-MM-DD): ")
date_object = datetime.strptime(input_date, "%Y-%m-%d")

days_to_subtract = int(input("Enter the number of days to subtract: "))

new_date = date_object - timedelta(days=days_to_subtract)

formatted_date = new_date.strftime("%Y-%m-%d")
print("The new date is:", formatted_date)

Feel free to customize the code as per your needs.