Get startedGet started for free

Taking differences of datetimes

1. Taking differences of datetimes

In this chapter you'll learn about arithmetic with datetimes.

2. Arithmetic for datetimes

What kind of arithmetic might you want to do with datetimes? You might want to subtract dates from each other to calculate the distances between, or you might want to add a timespan - something like a day, a week or two years - to a datetime to generate a new datetime, or you may even want to divide one timespan by another, to work out for example, how many weeks are in a certain interval. In this video, you'll revisit the subtraction of dates, before learning more about lubridate's special objects for handling time spans in later videos.

3. Subtraction of datetimes

Back in Chapter 1 you saw you could subtract one datetime from another to calculate the time between them. For example, the difference between the latest release of R, and the current date provided by Sys (dot) date. Behind the scenes it is the function difftime that is doing this calculation, and using difftime explicitly can give you more control over the results. To use difftime you simply pass in the two times that you want the difference for, and you will get the same result as using subtraction.

4. difftime()

The additional control comes from the units argument to difftime, which specifies the time unit for the difference. You can specify any one of secs, mins, hours, days or weeks. So, we can easily obtain the same time difference in seconds or weeks. If you don't specify the units argument, difftime will attempt to pick the units for you. Since, this may or may not be the units you expect it's good practice to explicitly set the units argument.

5. now() and today()

A particularly common task is to find out how long it's been since some event: perhaps how long since you ran an important report, or how long since the last update to your data. To do that you need today's date or datetime. lubridate provides two functions for just that. today gives you todays date as a Date object, and now gives you this very moment as a POSIXct object, both of which may be useful as one argument to difftime.

6. Let's practice!

OK, time to try this out!

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.