1. Intervals
Intervals are a third option in lubridate for storing time spans. Rather than representing an amount of time like a period or duration, they have a specific start and end datetime.
You can easily retrieve the amount of time the interval covers, either as a duration or period, but you can also do things like test whether another datetime is in the interval, or even if two intervals overlap. Let's take a closer look.
2. Creating intervals
An interval can be created from two datetimes, either using the interval function or the operator %--%.
Here's an interval that goes from the 5th January 1961 to 30th of January 1969, created both ways. This happens to be the interval between the first and last concerts by the Beatles.
3. Operating on an interval
lubridate provides a number of functions to operate on intervals. int_start and int_end extract the start and end of the interval.
4. Operating on an interval
int_length finds the length of the interval in seconds, or you can specifically ask for the interval as a period or duration with the as (dot) period and as (dot) duration functions.
5. Comparing intervals
To compare a datetime to an interval use the %within% operator, it will return TRUE if the datetime is inside the interval and FALSE otherwise. For example, is the day Jimi Hendrix played at Woodstock within the time the beatles were giving concerts? Nope.
To compare two intervals, use int_overlaps which will return TRUE if there are any times that are inside both intervals. You can check if Jimi Hendrix's touring period overlapped at all with the beatles. Yup, looks like it did.
6. Which kind of time span?
Now you've seen lubridate's three kinds of time span object: periods, durations and intervals, you might be wondering which one to use.
In general, if you have a "start" datetime and an "end" datetime, use an interval, since it's the most accurate way to store the span between two datetimes, and is easily converted to either a period or duration.
If you have in mind a length of time, but without a specific start or end you'll need a period or duration. Use a period if it's more important arithmetic reflects human imposed constructs like daylight savings or leap years, and use a duration if you are more interested in how many seconds have elapsed.
7. Monarchs of England
To practice you'll be working with a couple of datasets. The first is the reigns of kings and queens of england. The data come from Wikipedia, we've read in the start and end dates of their reigns and but you'll calculate the length of their reigns.
8. Halley's comet
The other data you'll see is about the appearance of Halley's comet. This data also comes from Wikipedia. You'll be figuring out which monarchs might have seen Halley's comet.
9. Let's practice!
Time for you to try intervals out.