Why does R add non-existing microseconds/nanoseconds to date-time objects?

Viewed 53

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.

1 Answers

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"

Related