Subtracting a Day from a Date in Python
When working with dates and times in Python, it's often necessary to shift them by a specific amount. A common operation is subtracting a day from a given date. Here's how to do it effectively:
Using the timedelta Object:
The most straightforward method is to use the timedelta object from the datetime module. This object allows you to adjust dates by various units of time, including days:
from datetime import datetime, timedelta # Create a datetime object d = datetime.today() # Create a timedelta object to subtract 1 day days_to_subtract = 1 delta = timedelta(days=days_to_subtract) # Subtract the delta from the datetime object d -= delta
This will decrement the date by one day, and the resulting d variable will hold the new datetime object.
Example:
d = datetime(2023, 3, 15) days_to_subtract = 1 d -= timedelta(days=days_to_subtract) print(d) # Output: 2023-03-14 00:00:00
Additional Considerations:
The above is the detailed content of How to Subtract a Day from a Date in Python?. For more information, please follow other related articles on the PHP Chinese website!