Professional Documents
Culture Documents
R DateAndTime
R DateAndTime
• Dates are represented by the Date class and can be coerced from a
character string using the as.Date() function
• x<-as.Date("2020/07/23")
•x
• class(x)
Dates in R
> ## Coerce a 'Date' object from character
> x<-as.Date("2020/07/23")
>x
[1] "2020-07-23"
> class(x)
[1] "Date”
To see the internal representation of a Date object by using the unclass() function
> unclass(x)
[1] 18466
Times in R
• Times are represented by the POSIXct or the POSIXlt class.
• POSIXct is just a very large integer under the hood.
• It use a useful class when you want to store times in something like a data
frame.
• POSIXlt is a list underneath and it stores a bunch of other useful
information like
• the day of the week, day of the year, month, day of the month. This is useful
when you need that kind of information.
POSIXlt and POSIXct function
x <- as.Date("2020-02-01")
y <- strptime("10 Jan 2020 09:00:00", "%d %b %Y %H:%M:%S")
#y <- strptime(" Feb 5, 2020 11:34:21", "%b %d, %Y %H:%M:%S")
x-y
> class(x)
[1] "Date"
> class(y)
[1] "POSIXlt" "POSIXt"
Additional Information
• Considers leap years, leap seconds, daylight savings, and time zones
x <- as.Date("2007-02-01")
y <- strptime("1 March 2007 09:00:00", "%d %b %Y %H:%M:%S")
x<-as.POSIXlt(x)
x-y