1

From the help of strptime and as.POSIXct, the POSIXlt and POSIXct classes seem only to record whole seconds.

(I need the milliseconds to pass them as a seed to a random number generator in a shared object.)

2 Answers 2

5

You can set the printed times to sub-second accuracy by changing the options:

options("digits.secs"=6)

The maximum is 6 digits - see options

Then you can get the system time to millisecond accuracy using:

as.POSIXlt(Sys.time())

That will print the time. To get the milliseconds since midnight that you're after simply use:

mySeed = as.POSIXlt(Sys.time())
mySeed = 1000*(mySeed$hour*3600 + mySeed$min*60 + mySeed$sec)
1
  • Thanks. I found this answer when I needed the intermediate midnight for other purposes: myMidnight = mySeed -mySeed$hour*3600 - mySeed$min*60 - mySeed$sec Then it is: as.numeric(difftime(mySeed,myMidnight,'secs'))*1000
    – Dave X
    Commented Dec 14, 2016 at 18:27
1

?Sys.time says:

On almost all systems it will have sub-second accuracy, possibly microseconds or better. On Windows it increments in clock ticks (usually 1/60 of a second) reported to millisecond accuracy.

So you can simply do this:

> foo <- Sys.time()
> foo
[1] "2014-05-22 12:40:55 CEST"
> hours <- as.POSIXlt(foo)$hour
> minutes <- as.POSIXlt(foo)$min
> seconds <- as.POSIXlt(foo)$sec
> hours*60*60*1000+minutes*60*1000+seconds*1000
[1] 45655771

In light of the help page, your results will depend on your system.

If you want to print the milliseconds, you can do this:

> options(digits.secs=3)
> foo
[1] "2014-05-22 12:40:55.771 CEST"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.