Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colon in date format between seconds and milliseconds. How to parse in R?

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"
like image 200
Dorian Mejer Avatar asked Nov 28 '12 20:11

Dorian Mejer


People also ask

How do I get milliseconds from DateTime?

To display the millisecond component of a DateTime valueParse(String) or DateTimeOffset. Parse(String) method. To extract the string representation of a time's millisecond component, call the date and time value's DateTime.

How do you format milliseconds?

Usually we display time in in 12 hour format hh:mm:aa format (e.g. 12:30 PM) or 24 hour format HH:mm (e.g. 13:30), however sometimes we also want to show the milliseconds in the time. To show the milliseconds in the time we include “SSS” in the pattern which displays the Milliseconds.


1 Answers

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") 
like image 142
Josh O'Brien Avatar answered Oct 02 '22 02:10

Josh O'Brien