W3docs

How to subtract a day from a date?

You can use the datetime module in Python to subtract a day from a date.

You can use the datetime module in Python to subtract a day from a date. Here's an example code snippet:

Subtract a day from a date in Python

python— editable, runs on the server

In this example, we first import the datetime and timedelta classes from the datetime module. We then define a date using the datetime class. To subtract a day from the date, we create a timedelta object with the number of days to subtract (in this case, 1) and subtract it from the date using the subtraction operator (-). The result is a new datetime object representing the date one day earlier than the original date.

Note: Avoid using date.replace(day=date.day-1) to subtract days, as it will raise a ValueError when the day is 1 and does not automatically handle month or year boundaries. The timedelta approach shown above is the standard and safest method.