Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a Millisecond Timestamp To a Time In R

I'm this has been asked before, but I just can't find the exact answer. If I have a number which represents milliseconds since midnight, say 34200577, how do I turn this into an R time?

like image 702
Craig Avatar asked Dec 26 '22 22:12

Craig


2 Answers

Construct a 'baseline time' at midnight, add the given millisecond once converted to seconds and interpret as a time:

R> as.POSIXct(as.numeric(ISOdatetime(2013,8,22,0,0,0)) + 34200577/1e3, 
+             origin="1970-01-01")
[1] "2013-08-22 09:30:00.576 CDT"
R> 

In fact, the shorter

R> ISOdatetime(2013,8,22,0,0,0) + 34200577/1e3
[1] "2013-08-22 09:30:00.576 CDT"
R>

works as well as ISOdatetime() returns a proper time object which operates in fractional seconds so we just apply the given offset.

This appears to be correct as

R> 34200577/1e3       # seconds
[1] 34200.6
R> 34200577/1e3/60    # minutes
[1] 570.01
R> 34200577/1e3/60/60 # hours
[1] 9.50016
R> 
like image 198
Dirk Eddelbuettel Avatar answered Jan 31 '23 08:01

Dirk Eddelbuettel


POSIXct uses 1970 as the origin of its time scale(measured in seconds.)

> time= as.POSIXct(34200577/1000 , origin=Sys.Date() )
> time
[1] "2013-08-22 02:30:00 PDT"

Note the discrepancy in results between Dirk's and my method. The POSIX times are input as assumed to occur in UCT, so there appeared the addition 8 hours for my location in UCT-8.

> difftime( as.POSIXct(34200577/1000 , origin=Sys.Date() ) , Sys.Date() )
Time difference of 9.50016 hours

You could get the time since midnight with:

 format( as.POSIXct(34200577/1000 , origin=Sys.Date(), tz="UCT" ),
          format="%H:%M:%S")
 [1] "09:30:00"
like image 26
IRTFM Avatar answered Jan 31 '23 09:01

IRTFM