Mike L
Mike L

Reputation: 496

Problems converting variable into proper datetime format in R

My data, DATA, has a variable, TIME, for which the values print out in this format: "11/14/2006 20:10". For TIME, its mode is numeric and its class is a factor.

I need to convert TIME to a proper date/time variable (DTIME) and add the new DTIME to DATA as date.time. I was told I may have to coerce the time values so that they follow the h:m:s format...Think character string manipulation. Below is my code:

 library("chron")

VAR=c(as.character(DATA$TIME))
DT<-t(as.data.frame(strsplit(VAR," ")))
DT[1:3,]
row.names(DT)<-NULL
DT[1:3,]
DTIME<-chron(dates=DT[,1],times=DT[,2],
        format=c("m/d/y","h:m"))

But once I run the last line of code, I get the following error message:

Error in convert.times(times., format = format[[2]]) : 
  format h:m may be incorrect
In addition: Warning message:
In is.na(out$s) : is.na() applied to non-(list or vector) of type 'NULL'

I don't understand what this means, much less how to fix it.

Upvotes: 1

Views: 5736

Answers (3)

CHP
CHP

Reputation: 17189

You can use as.POSIXct to convert string into time.

TIME <- "11/14/2006 20:10"
as.POSIXct(TIME, format="%m/%d/%Y %H:%M", tz='GMT')
## [1] "2006-11-14 20:10:00 GMT"

Upvotes: 1

G. Grothendieck
G. Grothendieck

Reputation: 269441

Its not clear from the question exactly what you have -- in such cases its best to show the output of dput applied to your variable -- but assuming you can convert it to character format using as.character or format then its just a matter of using as.chron :

> library(chron)
> TIME <- "11/14/2006 20:10"
> as.chron(TIME, "%m/%d/%Y %H:%M")
[1] (11/14/06 20:10:00)

Upvotes: 4

Victor K.
Victor K.

Reputation: 4094

Use lubridate - it's a fantastic library that will save you much effort.

library(lubridate)
x <- "11/14/2006 20:10"
> mdy_hm(x)
[1] "2006-11-14 20:10:00 UTC"

All lubridate's time conversion function follow a very similar pattern: e.g. "2013-04-01" can be parsed with ymd, etc.

Upvotes: 1

Related Questions