ivo Welch
ivo Welch

Reputation: 2866

R Day Difference is Fraction (Bug or Feature?)

it's a little surprising that the difference between two days ends up as a fraction, presumably because of some posix magic about seconds. alas, in this case, what is the recommended way to obtain the day difference? just add a little and convert to integer?

mydates <- c( as.POSIXct("2010-03-29") , as.POSIXct("2000-01-21") )
> mydates[1] - mydates[2]
Time difference of 3720 days
> as.numeric(mydates[1] - mydates[2])
[1] 3720
> (as.numeric(mydates[1] - mydates[2])) - 3720
[1] -0.04167

Upvotes: 0

Views: 93

Answers (2)

Qian
Qian

Reputation: 495

You can use timezone argument tz in as.POSIXct() and use the difftime() with the units argument set to "days" to avoid possible daylight saving time (DST) like this

date1 <- as.POSIXct("2010-03-29", tz = "UTC")
date2 <- as.POSIXct("2000-01-21", tz = "UTC")

day_difference <- difftime(date1, date2, units = "days")

Upvotes: 2

VinceGreg
VinceGreg

Reputation: 834

The difference is one hour, probably because of daylight saving time. You can specify a timezone (ex. tz = "UTC").

library(lubridate, warn.conflicts = FALSE)
library(dplyr, warn.conflicts = FALSE)

# base::as.POSIXct is using locale as timezone (Eastern time in my case)
mydates <- c( as.POSIXct("2010-03-29") , as.POSIXct("2000-01-21") )
mydates %>% strftime ( format ="%Y-%m-%d %H:%M:%S" ,tz ="UTC")
#> [1] "2010-03-29 04:00:00" "2000-01-21 05:00:00"

# One date is in daylight saving time , explaining 1 hour (1/24 days) of difference
lubridate::dst(mydates)
#> [1]  TRUE FALSE

(as.numeric(mydates[1] - mydates[2])) - 3720
#> [1] -0.04166667

1/24
#> [1] 0.04166667


# You can specify a timezone
datesUTC <-  c( as.POSIXct("2010-03-29", tz = "UTC") , as.POSIXct("2000-01-21" , tz = "UTC"))
datesUTC %>% strftime ( format ="%Y-%m-%d %H:%M:%S" ,tz ="UTC")
#> [1] "2010-03-29 00:00:00" "2000-01-21 00:00:00"

#Or using lubridate since the default consider UTC
c( ymd("2010-03-29") , ymd("2000-01-21") ) %>% strftime ( format ="%Y-%m-%d %H:%M:%S")
#> [1] "2010-03-29 00:00:00" "2000-01-21 00:00:00"

Created on 2024-05-31 with reprex v2.1.0

Upvotes: 5

Related Questions