带有自定义开始时间的日期时间(润滑)

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

是否可以使用自定义的开始时间而不是最早的时间来预定日期?

例如,每天的地板时间分为两个12小时间隔,从上午8点和晚上8点开始,而不是从上午12点和中午12点开始。

示例:

x <- ymd_hms("2009-08-03 21:00:00")
y <- ymd_hms("2009-08-03 09:00:00")
floor_date(x, '12 hours')
floor_date(y, '12 hours')

# default lubridate output:
[1] "2009-08-03 12:00:00 UTC"
[1] "2009-08-03 UTC"

# what i would like to have:
[1] "2009-08-03 20:00:00 UTC"
[1] "2009-08-03 08:00:00 UTC"


r datetime lubridate
1个回答
0
投票

您可以编写一个小switch

FUN <- function(x) {
  s <- switch(which.min(abs(mapply(`-`, c(8, 20), as.numeric(substr(x, 12, 13))))), 
              "08:00:00", "20:00:00")
  as.POSIXct(paste(as.Date(x), s))
}
FUN("2009-08-03 21:00:00")
# [1] "2009-08-03 20:00:00 CEST"

FUN("2009-08-03 09:00:00")
# [1] "2009-08-03 08:00:00 CEST"
© www.soinside.com 2019 - 2024. All rights reserved.