2

I have datetimes written in format "%d-%b-%Y %H:%M:%S.%OS", so for example "25-Apr-2021 18:31:56.234", that is to the precision of milliseconds. And when parse that to time object I see values are not the same, sometimes it adds 1 microsecond or decreases it, or similiar things. Why is this and what to do about this? I want to have a time object which is exactly 56 seconds and 234 milliseconds! (and zeroes after that if it needs to add higher precision

For example some of the values it prints when I call print(as.numeric(), digits=20) command: "1615310444.7509999 1615310442.5550001", or when I ask for difference between some 2 values, it gives: "Time difference of 0.003999949 secs" for example.

Vladimir
  • 1,243
  • 5
  • 19
  • 23
  • Can you show a reproducible example? – Bill O'Brien Jul 27 '21 at 15:55
  • For example some of the values it prints when I call print(as.numeric(), digits=20) command: "1615310444.7509999 1615310442.5550001", or when I ask for difference between some 2 values, it gives: "Time difference of 0.003999949 secs" for example. – Vladimir Jul 27 '21 at 15:58
  • 1
    @Vladimir the rounding off is happening due to the options digits in seconds. See my answer for reference. – vivek Jul 27 '21 at 16:07

1 Answers1

0

You can use the options(digits.secs) to show the milliseconds. Here is an example below. The digits.secs must be set at zero. Also note that you should change the format of the date

> dp <- options(digits.secs=0)
> dp
$digits.secs
[1] 0

> strptime("25-Apr-2021 18:31:56.234", format = "%d-%b-%Y %H:%M:%OS")
[1] "2021-04-25 18:31:56 +08"
> dp <- options(digits.secs=3)
> dp
$digits.secs
[1] 0

> strptime("25-Apr-2021 18:31:56.234", format = "%d-%b-%Y %H:%M:%OS")
[1] "2021-04-25 18:31:56.234 +08"

vivek
  • 301
  • 3
  • 13
  • But this only changes the way time objects are printed, it doesn't change the fact that internally my time object has some 'trash' micro/nanoseconds added, and this is true since we can see it in print(as.numeric(), digits=20) representation, is that right? – Vladimir Jul 27 '21 at 16:15
  • @Vladimir - another way to try would to try as.integer(date time object) This will help you calculate everything in milliseconds. – vivek Jul 27 '21 at 16:16