Home > Backend Development > Python Tutorial > How to Subtract a Day from a Datetime Object in Python?

How to Subtract a Day from a Datetime Object in Python?

Barbara Streisand
Release: 2024-11-21 00:12:14
Original
173 people have browsed it

How to Subtract a Day from a Datetime Object in Python?

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template