In this post, we will cover the basics of handling dates and times in R using the as.Date, as.POSIXct, and as.POSIXlt functions. We will use the example code below to explain each line in simple terms. Let’s get started!
Here is the script we are going to look at:
# the date objectSteve_online <-as.Date("1981-02-25")str(Steve_online) #Date[1:1], format: "1981-02-25
Date[1:1], format: "1981-02-25"
class(Steve_online) #Date
[1] "Date"
as.numeric(Steve_online) # stored as number of days since 1970-01-01
[1] 4073
as.numeric(as.Date("1970-01-01")) # equals zero
[1] 0
as.Date(as.Date("1970-01-01") +4073) # produces 1981-02-25 -- our original date
[1] "1981-02-25"
# vectors can contain multiple datesSteve_online <-as.Date(c("1981-02-25", "1997-01-12"))str(Steve_online)
Date[1:2], format: "1981-02-25" "1997-01-12"
Steve_online[2]
[1] "1997-01-12"
# what about POSIX?# POSIXct stores date time as integer == # seconds since 1970-01-01 UTCSteve_online <-as.POSIXct("1981-02-25 02:25:00", tz ="US/Mountain")as.integer(`Steve_online`)
[1] 351941100
# POSIXlt stores date time as list:sec, min, hour, mday, mon, year, wday, yday, isdst, zone, gmtoffSteve_online <-as.POSIXlt("1981-02-25 02:25:00", tz ="US/Mountain")as.integer(Steve_online) # no longer an integer
Warning: NAs introduced by coercion
[1] 0 25 2 25 1 81 3 55 0 NA NA
unclass(Steve_online) # this shows the components of the list
The first line of code creates a date object called Steve_online with the value of February 25, 1981, using the as.Date function. This function is used to convert a character string to a date object. The str function is then used to show the structure of the Steve_online object, which is of class Date.
The as.numeric function is used to convert the Steve_online object to the number of days since January 1, 1970 (known as the Unix epoch). This is a common way of representing dates in programming languages, and is useful for calculations involving dates. We also demonstrate that as.numeric(as.Date("1970-01-01")) returns zero, since this is the starting point of the Unix epoch.
We then show how to add or subtract days from a date object by adding or subtracting the desired number of days (as an integer) to the as.Date function with the reference date of January 1, 1970. In this case, we add 4073 days to January 1, 1970, resulting in the date of February 25, 1981 (our original date).
Next, we demonstrate how to create a vector of date objects by passing a character vector of dates to the as.Date function. The str function is used again to show the structure of the Steve_online object, which is now a vector of two date objects. We then show how to access the second element of the vector using indexing (Steve_online[2]).
Moving on to POSIX objects, we introduce the as.POSIXct function, which creates a POSIXct object that stores date time as an integer equal to the number of seconds since January 1,