[R] Dates as POSIXt

Daniel Haugstvedt daniel.haugstvedt at gmail.com
Mon Nov 5 08:51:17 CET 2012


When I try to do linear interpolation between financial contracts with maturities on different dates in different months I have come across some behavior I haven't seen before. 

I have a data frame in R which is loaded from an access database so I can't provide a working example. It was loaded using this code:

> dbPath <- "H:/pathToDB/DB.mdb"
> channel <- odbcConnectAccess(dbPath)
> DF  = sqlFetch(channel,'nameOfTable')

When I look at the Date column I get this result 
> str(DF$Date)
POSIXt[1:25311], format: "2003-09-03 06:00:00" "2003-09-03 06:00:00" ...

I have newer seen data as POSIXt, only as POSIXct or POSIXlt. It is the behavior of this class is that I would like more information about. Online searching have only told me that it is a virtual class. 

When I do some calculations to get the dates of maturity into the data frame I find this behavior. (For simplicity assume that the only month is March.)

> DF[,"DateOfMaturity"] = NA
> DF[,"DateOfMaturityPrevious"] = NA
> DF[,"DateOfMaturityNext"] = NA

> maturityFeb = 14
> maturityMar = 16
> maturityApr  = 15

> yearTmp = as.POSIXlt(DF$Date)$year+1900 
> DF$DateOfMaturity = as.POSIXct(strptime(paste(yearTmp,03,maturityMar ), "%Y %m %d"))
> DF$DateOfMaturityPrevious =  as.POSIXct(strptime(paste(yearTmp,02,maturityFeb ), "%Y %m %d")
> DF$DateOfMaturityNext = as.POSIXct(strptime(paste(yearTmp,04,maturityApr ), "%Y %m %d"))

which works fine and gives me the dates I want but it is not readable with human eyes. When I try 

> DF$DateOfMaturity =  as.POSIXlt(strptime(paste(yearTmp,03,maturityMar ), "%Y %m %d"))
> DF$DateOfMaturityPrevious =  as.POSIXlt(strptime(paste(yearTmp,02,maturityFeb ), "%Y %m %d")
> DF$DateOfMaturityNext =  as.POSIXlt(strptime(paste(yearTmp,04,maturityApr ), "%Y %m %d"))

it breaks my DF

> str(DF$DateOfMaturity)
List of 2015
$ : num [1:2015] 0 0 0 0 0 0 0 0 0 0 ...
$ : int [1:2015] 0 0 0 0 0 0 0 0 0 0 ...
$ : int [1:2015] 0 0 0 0 0 0 0 0 0 0 ...
$ : int [1:2015] 16 16 16 16 16 16 16 16 16 16 ...
$ : int [1:2015] 0 0 0 0 0 0 0 0 0 0 ...
$ : int [1:2015] 104 104 104 104 104 104 104 104 104 104 ...
$ : int [1:2015] 5 5 5 5 5 5 5 5 5 5 ...
$ : int [1:2015] 15 15 15 15 15 15 15 15 15 15 
 .
 .
 .
[list output truncated]

Now I wonder why I can't use POSIXlt in my data frame (I know I shouldn't but that is not the question) and if I can use POSIXt like the original data?  It is human readable but also suited for calculation (e.g. DF$Date >  as.POSIXct("2005-12-01") works nicely.


Best regards
Daniel Haugstvedt
Ph.D. student
NTNU, Trondheim, Norway



More information about the R-help mailing list