user1471980
user1471980

Reputation: 10646

converting time to POSIXct in R

I have a data frame that can have values like this:

p<-c("2012-08-14 9:00", "2012-08-14 7:00:00")

I am trying to conver to datetime as this:

p<-as.POSIXct(p)

this converted everyting to to 2012-08-14 09:00:00

for some reason, it is not working anymore. If you have noticed, my data sometimes have seconds and somtimes it does not. How do you force this to be datetime format?

I get errors like this:

Error in as.POSIXlt.character(p) : 
  character string is not in a standard unambiguous format

Upvotes: 1

Views: 3135

Answers (2)

user1043144
user1043144

Reputation: 2710

the package lubridate may help
here an example - perhaps not the most elegant one - but it hs

p<-c("2012-08-14 9:00", "2012-08-14 7:00:00")

require(lubridate) # 


NewDate <- c()
for (i in 1 : 2)
        {
          if (nchar(unlist(strsplit(p[i], ' '))[2]) == 4) {NewDate <- c(NewDate,       as.character(ymd_hm(p[i])))}
          if (nchar(unlist(strsplit(p[i], ' '))[2]) == 7) {NewDate <- c(NewDate, as.character(ymd_hms(p[i])))}
        }
NewDate

Upvotes: 0

Joshua Ulrich
Joshua Ulrich

Reputation: 176718

Your vector isn't in a consistent format, so convert it to POSIXlt first because as.POSIXlt.character checks multiple formats.

p <- c("2012-08-14 9:00", "2012-08-14 7:00:00")
plt <- as.POSIXlt(p)
pct <- as.POSIXct(plt)

Upvotes: 4

Related Questions