I am calculating differences in two date times, using the difftime
function in R
and getting a wrong answer, here is the code
t1 <- as.POSIXct("7/18/2005 8:30:00", format = "%m/%d/%Y %H:%M:%S")
t2 <- as.POSIXct("10/30/2005 8:30:00", format = "%m/%d/%Y %H:%M:%S")
difftime(t2,t1,units = "hours")
I am getting the following answer
Time difference of 2497 hours
which I know is wrong, as both t1
and t2
have the same time
value, so they should be separated by an exact multiple of 24 hours (i.e., the correct answer is 2496 hours, not 2497 - also confirmed by other tools such as excel, google sheets).
Any idea, why R
is giving me the wrong result?
You gained an hour due to Daylight Savings Time changeover (Sunday 10/30/2005 02:00:00)
You can modify this by doing as.POSIXct(..., tz = 'UTC')
with whatever timezone it's supposed to be; UTC to make things unambiguous and avoid DST changes.
If you want to modify the default timezone for all as.POSIXct()
calls, see How to change the default time zone in R?, which suggests:
Sys.setenv(TZ='GMT')
orTZ="UTC"
into Renviron.site