Working with durations

1. Working with durations

Much like dates, datetimes have a kind of arithmetic; we can compare them, subtract them, and add intervals to them. Because we are working with both days and times, the logic for durations is a little more complicated, but not by much. Let's have a look.

2. Working with durations

Just as with dates, to get a sense for what's going on we put our datetimes on a timeline. These two datetimes here correspond to the start and end of one ride in our data set.

3. Working with durations

To follow along in Python, we'll load these two in as "start" and "end". When we subtract datetimes, we get a timedelta. A timedelta represents what is called a duration: the elapsed time between events.

4. Working with durations

When we call the method total_seconds(), we get back the number of seconds that our timedelta represents. In this case, 1450 seconds elapsed between our start and end. 1450 seconds is 24 minutes and 10 seconds.

5. Creating timedeltas

You can also create a timedelta by hand. You start by importing timedelta from datetime. To create a timedelta, you specify the amount of time which has elapsed. For example, we make delta1, a timedelta which corresponds to a one second duration.

6. Creating timedeltas

Now when we add delta1 to start, we see that we get back a datetime which is one second later.

7. Creating timedeltas

We also create a timedelta, delta2, which is one day and one second in duration. Now when we add it to start, we get a new datetime which is the next day and one second later. Timedeltas can be created with any number of weeks, days, minutes, hours, seconds, or microseconds, and can be as small as a microsecond or as large as 2-point-7 million years.

8. Negative timedeltas

Timedeltas can also be negative. For example, if we create delta3, whose argument is -1 weeks, and we add it to start we get a datetime corresponding to one week earlier.

9. Negative timedeltas

We can also subtract a positive timedelta and get the same result. We create delta4, which corresponds to a 1 week duration, and we subtract it from start. As you can see, we get the same answer as when we added a negative timedelta.

10. Working with durations

In this lesson, we showed how to create timedeltas, which represent a duration of time. You can create timedeltas by subtracting two datetimes, which tells you how much time has elapsed between events. You can also create a timedelta directly, then add and subtract timedeltas from datetimes to make new datetimes. In the next few exercises, you'll see how these pieces can be combined together to answer more complex questions.