Times & Dates

Intermediate R

Filip Schouwenaars

DataCamp Instructor

Today, right now!

today <- Sys.Date()
today
"2015-05-07"
class(today)
"Date"
now <- Sys.time()
now
"2015-05-07 10:34:52 CEST"
class(now)
"POSIXct" "POSIXt"
Intermediate R

Create Date objects

my_date <- as.Date("1971-05-14")
my_date
"1971-05-14"
class(my_date)
"Date"
Intermediate R

Create Date objects

my_date <- as.Date("1971-14-05")
Error: character string is not in a standard unambiguous format
my_date <- as.Date("1971-14-05", format = "%Y-%d-%m")
my_date
"1971-05-14"
Intermediate R

Create POSIXct objects

my_time <- as.POSIXct("1971-05-14 11:25:15")
my_time
"1971-05-14 11:25:15 UTC"
Intermediate R

Date arithmetic

my_date
"1971-05-14"
my_date + 1
"1971-05-15"
my_date2 <- as.Date("1998-09-29")
my_date2 - my_date
Time difference of 10000 days
Intermediate R

POSIXct arithmetic

my_time
"1971-05-14 11:25:15 UTC"
my_time + 1
"1971-05-14 11:25:16 UTC"
my_time2 <- as.POSIXct("1974-07-14 21:11:55 UTC")
my_time2 - my_time
Time difference of 1157.407 days
Intermediate R

Under the hood

my_date
"1971-05-14"
unclass(my_date)
498
my_time
"1971-05-14 11:25:15 CET"
unclass(my_time)
43064715
attr(my_time, "tzone")
""
Intermediate R

Dedicated R Packages

  • lubridate
  • zoo
  • xts
Intermediate R

Let's practice!

Intermediate R

Preparing Video For Download...