Wednesday, March 7, 2012

Some time conversions in R

Form a "POSIXlt" object from a string :
tt = strptime("20100101","%Y%m%d", tz="GMT")

Compute the seconds since 1970 ((Internal storage format of the "POSIXlt" class)
as.double(tt)

Compute the days since 1970 (Internal storage format of the "Date class)
as.double(as.Date(tt))
or
unclass(as.Date(tt)) 

Convert an xts object into seconds since 1970
xx = xts(111, tt)
as.double(time(xx))

Convert an xts object into days since 1970
floor(as.double(time(xx))/60/60/24)

Construct a time object from different numeric components
ISOdatetime(year, month, day, hour, min, sec, tz = "")

Extract from a POSIXlt object the Year, month, day  etc information in numeric format :
class(a)
[1] "POSIXlt" "POSIXt"

a
[1] "2009-07-06 20:00:28"

c(a$year+1900, a$mon+1, a$mday, a$hour, a$min, a$sec)
[1] 2009    7    6   20    0   28

No comments:

Post a Comment