9

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
puretppc
  • 3,232
  • 8
  • 38
  • 65
stokeinfo
  • 135
  • 1
  • 2
  • 8

2 Answers2

14

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.

Justin
  • 42,475
  • 9
  • 93
  • 111
2

If your goal is to obtain a string with the time, you can use regular expressions in sub. If you use strptime on a string with no date information, today's date is used.

x <- "2/7/2013 7:43"

x2 <- sub(".* ", "", x)
# [1] "7:43"

strptime(x2, "%R")
# [1] "2014-02-05 07:43:00"
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
  • Can you explain to me the gist of the 3 regular expression items in the sub function? I am fairly new to regexpressions. Thanks for the help! – stokeinfo Feb 05 '14 at 20:41
  • @stokeinfo Have a look at `?sub`. The three arguments are: pattern, replacement, string. The pattern `.* ` means: Any number of characters followed by a space. The replacement is just the empty string. The function replaces the space and all characters preceding the space with the empty string. Hence, only the string denoting the time remains. – Sven Hohenstein Feb 05 '14 at 20:49
  • Or in other words, sub looks for the pattern and replaces it with "nothing", which effectively deletes the date from the string and just leaves the time? – stokeinfo Feb 05 '14 at 20:54
  • Boom boom. Thank you very much! – stokeinfo Feb 05 '14 at 20:59
  • Last thing out of curiosity... How would you extract the date with the same method? – stokeinfo Feb 05 '14 at 21:00
  • @stokeinfo `sub(" .*", "", x)` – Sven Hohenstein Feb 05 '14 at 21:06