as.Date not preserving hour and min information in R
date, posixct, r
Solution
You want a Datetime class such as `POSIXct` (or the expanded form `POSIXlt`), and not Date. See `help(DateTimeClasses)`.
Saying that `Date` discards hours and minutes is equivalent to saying that integers discard the part after the decimal -- that is the point. [ In fact, dates are often represented as integers but that is different here too as it really is fractional days, but I digress. ]
In a nutshell, if you do not have intra-day information, use `Date`. In all other cases, use `POSIXct`.
Problem
I read in a csv to a data frame as follows: ``` data <- read.csv("Prices.csv", stringsAsFactors = FALSE) data$Timestamp <- as.POSIXct(data$Timestamp, format="%m/%d/%y %H:%M") ``` I tried to use the below but the hour and min data was removed which is my question. How can this be used with as.Date but preserving all info? ``` data$Timestamp <- as.Date(data$Timestamp, format="%m/%d/%y %H:%M") ``` This is what data$Timestamp looks like using the as.POSIXct command above which is fine: ``` head(data$Timestamp) [1] "2013-11-01 09:31:00 EDT" "2013-11-01 09:32:00 EDT" "2013-11-01 09:34:00 EDT" "2013-11-01 09:35:00 EDT" [5] "2013-11-01 09:36:00 EDT" "2013-11-01 09:37:00 EDT" ``` This is a few data points from the original csv file: ``` Timestamp 11/1/13 9:31 11/1/13 9:32 11/1/13 9:34 11/1/13 9:35 11/1/13 9:36 11/1/13 9:37 ``` Thank you.