Suppose you want to find the future date or the past date quickly. Of course, there can be many ways to find it. But the quickest way to find the future and past date is the Python timedelta. In this entire tutorial, you will know how to use timedelta in python with steps.
In this entire section, you will know all the steps to implement python timedelta. Follow all the steps to correctly implement timedelta.
The first step is to import all the required libraries to implement python timedelta. You can import the library using the import statement.
from datetime import datetime
from datetime import timedelta
In order to implement the python timedelta you have to find the base time. For example, I am using the present time and date as the base time. In python, you can find today’s date and time using the now() method. Execute the following code to find it.
now = datetime.now()
print(now)
Output
After the above steps let’s implement the examples on finding the past and the future date.
Let’s find the date from now after 365 days. To do so you have to use the timedelta(days=365).
print(str(now + timedelta(days=365)))
Output
Find the date after two weeks. Again to find you have pass the weeks=2 as an argument inside the timedelta() method. Execute the code below.
print(str(now + timedelta(weeks=2)))
Output
In this same way, you can find the past date using the timedelta. To do so you have to just subtract the current time.
For example, let’s calculate the time one year ago. Then you have to subtract the current time with timedelta(days=365).
print(str(now - timedelta(days=365)))
Output
Now let’s find the date two weeks ago. Then you have to subtract timedelta(weeks=2) from the now. Execute the below code and see the output.
print(str(now - timedelta(weeks=2)))
Output
The timedelta() method is the quickest way to manipulate date and time in python. These are the examples on timedelta. Hope you have liked this tutorial. If you have any queries then you can contact us for more information.
Source: