Subtracting a Day from a Date in Python
Determining the best approach to subtract a day from a given Python datetime object is a common programming challenge. Here, we delve into a reliable method using a timedelta object:
Method:
To subtract a day from a datetime object (d), you can leverage the timedelta class from the datetime module:
from datetime import datetime, timedelta days_to_subtract = 1 # Replace with the desired number of days d = datetime.today() - timedelta(days=days_to_subtract)
This operation creates a timedelta object representing the number of days to subtract and then subtracts it from the datetime object d. The resulting variable d will contain the adjusted date that is one day fewer than the original date.
The above is the detailed content of How to Subtract a Day from a Datetime Object in Python?. For more information, please follow other related articles on the PHP Chinese website!