
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to subtract Python timedelta from date in Python?
The Python datetime module provides various ways for manipulating dates and times. One of its key features is the timedelta object, which represents duration and also the difference between two dates or times.
Subtracting a specific amount of time from a date can be done using timedelta. For example, if we want to find the date a day before today, then we create a timedelta object with days=1 and then subtract it from the current date.
Subtracting One Day from Today's Date Using timedelta
The basic use case is subtracting a single day from today's date. This can be done by creating a timedelta object representing one day and then subtracting it from the current datetime.
Example
In the following program, we use datetime.today() to get the current date and time. Later, we subtract a timedelta(days=1) object from it to get the date and time exactly one day before.
from datetime import datetime, timedelta today = datetime.today() yesterday = today - timedelta(days=1) print("Today:", today) print("Yesterday:", yesterday)
Following is the output of the above code:
Today: 2025-05-12 16:00:00.123456 Yesterday: 2025-05-11 16:00:00.123456
Subtracting Hours from a Date Using timedelta
We can also subtract a number of hours or seconds from a date using timedelta. Mostly, this method is used when working with time intervals shorter than a day.
Example
Here, the timedelta constructor takes hours as a parameter. We subtracted timedelta(hours=5) from the current date and time, as a result, it gives the exact time five hours earlier:
from datetime import datetime, timedelta now = datetime.now() five_hours_ago = now - timedelta(hours=5) print("Now:", now) print("5 Hours Ago:", five_hours_ago)
Following is the output of the above code:
Now: 2025-05-12 16:00:00.123456 5 Hours Ago: 2025-05-12 11:00:00.123456