How to Use the Timedelta Class in Python 


               


How to Use the Timedelta Class in Python



Python


In this article, we show how to use the timedelta class in Python.

With the timedelta class in Python, we can find a future date or a past date.

Delta means change. Therefore, time delta means the change in time.

What we do in Python is we create a date object and then we create a timedelta.

If we add this timedelta to the date object, we get a future date.

If we subtract this timedelta from the date object, we get a past date.

The value we specify for the timedelta must be an integer. And this value represents the number of days.

Therefore, if we have the date, 1/5/2010 and we have a timedelta of 2 and add this timedelta to the date, then we get a date of 1/7/2010. If we subtract this timedelta from the date, we get the date of 1/3/2010

So in the following code below, we create a date object and then show how to use a timedelta to get a past date and a future date from it.



So let's now go over this code.

So the first thing we have to do is import the datetime module. The datetime module allows us to create date objects in Python and use the timedelta class.

We then create a variable, date1, and set it equal to, datetime.date(2010, 6,15)

This creates then date, 6/15/2010

We then create a variable, td, and assign the timedelta value of 2 to it. Therefore, this represents 2 days.

We create a variable, futuredate, and add the timedelta to the date object.

When we print this futuredate variable, we get the date, 2010-06-17, which is 2 days ahead of our date object, 6/15/2010.

We then do this for the past date.

We create a variable, pastdate, and assign it to the date object minus the timedelta. This creates the date 2 days prior to our date object, which is 2010-06-13.

After this, we create a new timedelta. We create a timedelta of 100.

100 days after 6/15/2010 is 2010-09-23.

Next, we go to a more real-life example.

Say we're a clinic and we schedule appointments for patients.

You want to get today's date and then usually for clinics, there's various follow-up appointments. So in this example, we do 30-day and 60-day followup appointments. And this is exactly what we do. We first create a timedelta of 30 and add it to today's date. And then we create a time delta of 60 and add it to today's date. This creates our 30- and 60-day follow-up appointments.

And this is how we can use the timedelta class in Python to get future or past dates by specifying the number of days.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...