Extracting time from character string with strptime() in R, returning NA

stokeinfo picture stokeinfo · Feb 5, 2014 · Viewed 17.8k times · Source

I am trying to extract out the time from a character string in R and can't stop getting NA as a result. I have tried numerous variations of the regular expression tags, but can't seem to get around this simple problem. Any help/clarifications are appreciated.

Here is my code for an example:

> x
[1] "2/7/2013 7:43"
> class(x)
[1] "character"
> z <- strptime(x, "%H:%M")
> z
[1] NA

Answer

Justin picture Justin · Feb 5, 2014

R doesn't know that your string is a datetime. So make it one first:

y <- strptime(x, format='%m/%d/%Y %H:%M')

If you were trying to get just the date, you could do:

strptime(x, '%m/%d/%Y') 

Because strptime discards any extra characters past your format string, but you cannot grab the trailing %H:%M because the function doesn't know where to start.

Once it is a proper datetime class, you can do things to it:

strftime(y, '%H:%M')

I prefer to use as.POSIXlt rather than strptime and format instead of strftime... but they are roughly equivalent.