Taking differences of datetimes

Working with Dates and Times in R

Charlotte Wickham

Instructor

Arithmetic for datetimes

  • datetime_1 - datetime2: Subtraction for time elapsed
  • datetime_1 + (2 * timespan): Addition and multiplication for generating new datetimes in the past or future
  • timespan1 / timespan2: Division for change of units
Working with Dates and Times in R

Subtraction of datetimes

releases <- read_csv("rversions.csv")
last_release <- filter(releases, date == max(date))
Sys.Date() - last_release$date
Time difference of 99 days
difftime(Sys.Date(), last_release$date)
Time difference of 99 days

time1 - time2 is the same as difftime(time1, time2)

Working with Dates and Times in R

difftime()

units = "secs", "mins", "hours", "days", or "weeks"

difftime(Sys.Date(), last_release$date, units = "secs")
Time difference of 8553600 secs
difftime(Sys.Date(), last_release$date, units = "weeks")
Time difference of 14.14286 weeks
Working with Dates and Times in R

now() and today()

today()
"2017-10-07"
str(today())
 Date[1:1], format: "2017-10-07"
now()
"2017-10-07 09:44:52 PDT"
str(now())
 POSIXct[1:1], format: "2017-10-07 09:44:59"
Working with Dates and Times in R

Let's practice!

Working with Dates and Times in R

Preparing Video For Download...