Dates and Times in R

 

Dealing with dates

Dates are represented by
the Date class Times are represented by the POSIXct or the POSIXlt
class Dates and times are stored internally as the number of days and
seconds since 1970-01-01 respectively.

date=as.Date("2013-12-11")
date
## [1] "2013-12-11"
class(date)
## [1] "Date"

POSIXct store time
similar to a data frame POSIXlt is a list containing day of the week,
day of the year, month, day of the month

#to figure our the day of the "date", try
weekdays(date)
## [1] "Wednesday"
#to figure our the month of the "date", try
months(date)
## [1] "December"
#to figure out the quarter of the year, try
quarters(date)
## [1] "Q4"

Dealing with time

Class “POSIXct”
represents the (signed) number of seconds since the beginning of 1970
(in the UTC timezone) as a numeric vector. Class “POSIXlt” is a named
list of vectors representing sec, min etc as elaborated below.

my_time<-Sys.time()
my_time
## [1] "2014-08-12 16:43:03 EDT"
#convert system time to POSIXlt
t1_Xlt <- as.POSIXlt(my_time)
t1_Xlt
## [1] "2014-08-12 16:43:03 EDT"
#unclass and use name function to see parameters that can be stored
names(unclass(t1_Xlt))
## [1] "sec"   "min"   "hour"  "mday"  "mon"   "year"  "wday"  "yday"  "isdst"
#now you can get all in information about time
t1_Xlt$sec  #0-61 secs
## [1] 3.024
t1_Xlt$min  #0-59 mins
## [1] 43
t1_Xlt$hour #0-23 hours
## [1] 16
t1_Xlt$mday #1-31st day of the month
## [1] 12
t1_Xlt$mon  #1-11 month since the first of the year
## [1] 7
t1_Xlt$year # since 1900
## [1] 114
t1_Xlt$wday #0-6 day of the week, starting on Sunday.
## [1] 2
t1_Xlt$yday #0-365: day of the year.
## [1] 223
t1_Xlt$isdst #Daylight Savings Time flag. Positive if in force, zero if not, negative if unknown.
## [1] 1

strptime

Functions to convert
between character representations and objects of classes “POSIXlt” and
“POSIXct” representing calendar dates and times.

date <- c("December 13, 2013 7:40", "December 23, 2014 8:40")
fixed_time <- strptime(date, "%B %d, %Y %H:%M")
fixed_time
## [1] "2013-12-13 07:40:00" "2014-12-23 08:40:00"
class(fixed_time)
## [1] "POSIXlt" "POSIXt"

 

Leave a Comment

Your email address will not be published. Required fields are marked *