R 日差是分数(错误还是功能?)

问题描述 投票:0回答:2

有点令人惊讶的是,两天之间的差异最终变成了一个分数,大概是因为一些关于秒的 posix 魔法。 唉,在这种情况下,推荐的获取日差的方法是什么? 只需添加一点并转换为整数?

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
r posixct
2个回答
0
投票

选项 1:由于差异很小,只需使用

round()
即可取回整数:

mydates <- c( as.POSIXct("2010-03-29") , as.POSIXct("2000-01-21") )

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

选项 2:使用

{lubridate}
包:

mydates <- c( lubridate::as_date("2010-03-29") , lubridate::as_date("2000-01-21") )

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

0
投票

相差一小时,可能是因为夏令时的缘故。您可以指定时区(例如。

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"

创建于 2024-05-31,使用 reprex v2.1.0

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.