R Language Date and Time

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

R comes with classes for dates, date-times and time differences; see ?Dates, ?DateTimeClasses, ?difftime and follow the "See Also" section of those docs for further documentation. Related Docs: Dates and Date-Time Classes.

Remarks

Classes

  • POSIXct

    A date-time class, POSIXct stores time as seconds since UNIX epoch on 1970-01-01 00:00:00 UTC. It is the format returned when pulling the current time with Sys.Time().

  • POSIXlt

    A date-time class, stores a list of day, month, year, hour, minute, second, and so on. This is the format returned by strptime.

  • Date The only date class, stores the date as a floating-point number.

Selecting a date-time format

POSIXct is the sole option in the tidyverse and world of UNIX. It is faster and takes up less memory than POSIXlt.

origin = as.POSIXct("1970-01-01 00:00:00", format ="%Y-%m-%d %H:%M:%S", tz = "UTC")

origin
## [1] "1970-01-01 UTC"

origin + 47
## [1] "1970-01-01 00:00:47 UTC"

as.numeric(origin)     # At epoch
## 0

as.numeric(Sys.time()) # Right now (output as of July 21, 2016 at 11:47:37 EDT)
## 1469116057

posixlt = as.POSIXlt(Sys.time(), format ="%Y-%m-%d %H:%M:%S", tz = "America/Chicago")

# Conversion to POISXct
posixct = as.POSIXct(posixlt)
posixct

# Accessing components
posixlt$sec   # Seconds 0-61
posixlt$min   # Minutes 0-59
posixlt$hour  # Hour 0-23
posixlt$mday  # Day of the Month 1-31
posixlt$mon   # Months after the first of the year 0-11
posixlt$year  # Years since 1900.

ct = as.POSIXct("2015-05-25")
lt = as.POSIXlt("2015-05-25")

object.size(ct)
# 520 bytes
object.size(lt)
# 1816 bytes

Specialized packages

  • anytime
  • data.table IDate and ITime
  • fasttime
  • lubridate
  • nanotime


Got any R Language Question?