Get startedGet started for free

Time spans.

1. Time spans

Time spans are hard because they don't have a constant meaning. You saw an example in the previous exercise. Even though we say two datetimes are a day apart, that doesn't mean they are exactly 86400 seconds apart. To do addition with datetimes and timespans you need to be specific about what you mean by a time span. For example, to add one day to a datetime, you need to define what you mean by "one day".

2. Time spans in lubridate

lubridate does this by providing two different kinds of time span: periods and durations. Periods are designed to match our human concept of a time span. For example if we take a datetime and add a period of one day, we get the same time the next day, regardless of whether that is 86400 seconds in the future or not. Durations are simply a fixed length of time in seconds, more like how a stopwatch measures time. If we take a datetime and add a duration of one day, we get the datetime 86400 seconds in the future.

3. Creating a time span

To create a period in lubridate you use the function of the appropriate unit in plural form. For example if we want a period of 1 day, we use the days function. Calling days results in a period of one day. The period constructors take a single argument x which by default is 1, but you can specify some other multiple of the time span. A duration is constructed similarly, except the duration functions all start with d. So, to construct a duration of 2 days, you use the ddays function. You'll notice periods and durations print a little differently to help remind you of their meaning.

4. Arithmetic with time spans

Once you have a time span you can multiply it by a number, add it to or subtract it from other time spans, or add it to or subtract it from a datetime.

5. Functions to create time spans

There's a constructor for each unit of time. Just remember they are plural - that is they end in s and that durations are always prefaced with a d.

6. Let's practice!

In the exercises you'll explore how periods and durations differ and how you can use them to generate sequences of datetimes.