9

How can I parse this date format? Should I change this colon to dot or maybe someone know better solution?

> x <- "2012.01.15 09:00:02:002"
> strptime(x, "%Y.%m.%d %H:%M:%S:%OS") 
[1] "2012-01-15 09:00:02"
> strptime(x, "%Y.%m.%d %H:%M:%OS")
[1] "2012-01-15 09:00:02"
> x <- "2012.01.15 09:00:02.002"
> strptime(x, "%Y.%m.%d %H:%M:%OS")
[1] "2012-01-15 09:00:02.001"
Dorian Mejer
  • 115
  • 1
  • 5

2 Answers2

8

There's a subtle distinction here that may be throwing you off. As ?strptime notes:

for 'strptime' '%OS' will input seconds including fractional seconds.

To emphasize that a bit, %OS represents the seconds including fractional seconds --- not just the fractional part of the seconds: if the seconds value is 44.234, %OS or %OS3 represents 44.234, not .234

So the solution is indeed to substitute a . for that final :.

Here's one way you might do that:

x <- "2012.01.15 09:00:02:002"
strptime(gsub(":", ".", x), "%Y.%m.%d %H.%M.%OS") 
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
  • +1. I think the OP already knew all that -- you'll note that (s)he uses that fact in the last thing (s)he tried -- but it's likely to be useful to other people who might be coming across this question. – ruakh Nov 28 '12 at 21:01
  • @ruakh -- Good point, and I suspect you're right. I like that the quote from `?strptime` makes the point extra unambiguous. – Josh O'Brien Nov 28 '12 at 21:19
  • Yes indeed i've converted colon to dots. Thx for quick reply :) – Dorian Mejer Nov 28 '12 at 21:22
2

Would

strptime(gsub(":", ".", x), "%Y.%m.%d %H.%M.%OS3")

be cheating?

ruakh
  • 175,680
  • 26
  • 273
  • 307
  • `sub` will only replace the first instance of a `:` with a `.` rather than each instance. you'll need `gsub` for that as per @JoshO'Brien's answer – Justin Nov 28 '12 at 21:00
  • @Justin: I think I'd actually already fixed that by the time you commented, but thank you. :-) – ruakh Nov 28 '12 at 21:02