Timestamp analysis in milliseconds to time in R

I already asked, but I definitely can’t find the exact answer. If I have a number that represents milliseconds since midnight, say 34200577, how can I turn this into R-time?

+4
source share
3 answers

Build the "base time" at midnight, add the given millisecond after converting to seconds, and interpret it as 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, shorter

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

works, and ISOdatetime() returns the correct temporary object, which works in fractional seconds, so we just apply the specified offset.

That seems right, because

 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> 
+6
source

POSIXct uses 1970 as the source 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 inconsistency of the results between Dirk and my method. POSIX time is entered as estimated in UCT, so in UCT-8 8 hours appeared for my location.

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

You can get time from midnight:

  format( as.POSIXct(34200577/1000 , origin=Sys.Date(), tz="UCT" ), format="%H:%M:%S") [1] "09:30:00" 
+2
source

A little "gottcha" which I think is worth pointing out ...

In R 3.1.2 for Windows 64 bit, I get the following results for a Dirk example

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

Pay attention to the absence of fractional seconds. This is due to the setting of the "digits.secs" parameter

 > getOption("digits.secs") NULL 

Setting this option as follows gives the expected result:

 > options(digits.secs=3) > ISOdatetime(2013,8,22,0,0,0) + 34200577/1e3 [1] "2013-08-22 09:30:00.576 BST" 

As you can guess, this is due to the formatting of the output, and not to the actual values ​​that we get from our date arithmetic. See ?strptime and ?strptime for documentation on this.

+2
source

Source: https://habr.com/ru/post/1498512/


All Articles