3

I want to convert current time to epoch timestamp with microseconds in R. For that I am running following code.

options(digits.secs = 6)
now = Sys.time()    
as.double(now)

When I simply print now the output is "2017-11-11 20:40:18.370305 CET" where it is capturing microseconds but when I convert it to epoch timestamp using as.double(now), the microsecond precision is gone. The result is only 1510429218. How to retain the microseconds?

Chadwick Robbert
  • 1,026
  • 1
  • 11
  • 23

2 Answers2

1

Learned how R handles decimal digits very hard way! See following code.

options(digits.secs = 6)    
a = c(as.double(Sys.time()), as.double(Sys.time()), as.double(Sys.time()))
print(a)

The output of this code is following.

[1] 1510430216 1510430216 1510430216

Timestamps seem to have lost their microsecond precision. But when the data is written to file or exported it the decimal digits are visible.

df = data.frame(a)
write.csv(x = df, file = "test.csv")

Contents of the file are:

1 1510430215.888998
2 1510430215.889942
3 1510430215.889942

To also see the decimal digits in R session/console, visibility options need to be changed.

options(digits = 16)
print(a)

Now all the decimal digits are visible in R session too!

[1] 1510430215.888998 1510430215.889942 1510430215.889942

The default display digits are only 7. So if the number is greater than that, R simply chooses to discard decimal digits from displaying! It is ridiculous as it creates massive confusion. At least one or two decimal digits should be kept.

Chadwick Robbert
  • 1,026
  • 1
  • 11
  • 23
0

You do (always) have them, but you need to tell print to use more digits:

R> n <- Sys.time()
R> print(as.numeric(n), digits=16)    ## digits matters here
[1] 1510432192.721936
R> n
[1] "2017-11-11 14:29:52.721935 CST"
R> 
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725