R Lubridate:将日期时间舍入/对齐到一天中最接近的任意时间?

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

我有一个日期时间列表,如下所示:

data <- data.frame(datetimes = c(ymd_hms("2024-01-01 04:12:35"), 
                                 ymd_hms("2024-04-01 14:52:20"), 
                                 ymd_hms("2024-03-18 23:43:56")))

我想将每个日期时间四舍五入/对齐到一天中指定时间的下一个出现位置。

例如,如果我选择时间

10:30:00
,我想对每个日期进行四舍五入,以便:

2024-01-01 04:12:35
变为 ->
2024-01-01 10:30:00

2024-04-01 14:52:20
变为 ->
2024-04-02 10:30:00

2024-03-18 23:43:56
变为 ->
2024-03-19 10:30:00

有没有办法轻松做到这一点?

谢谢

r datetime dplyr lubridate zoo
1个回答
1
投票

1) 如果日期时间超过 10:30:00,则在日期中添加 1,然后粘贴 10:30:00 并转换回 POSIXct。

library(dplyr)
library(lubridate)

cutoff <- 10:30:00" # specify as string
data %>%
  mutate(datetimes2 = 
    (as.Date(datetimes) + (sub(".* ", "", datetimes) > cutoff)) %>%
    paste(cutoff) %>% 
    ymd_hms)

##             datetimes          datetimes2
## 1 2024-01-01 04:12:35 2024-01-01 10:30:00
## 2 2024-04-01 14:52:20 2024-04-02 10:30:00
## 3 2024-03-18 23:43:56 2024-03-19 10:30:00

2) 交替减去 10.5*3600,提取 Dte,加 1,然后再添加第二个。

cutoff <- 10.5 * 3600 # specify in seconds
data %>%
  mutate(datatimes2 = as.POSIXct(as.Date(datetimes-cutoff)+1) + cutoff)

##             datetimes          datatimes2
## 1 2024-01-01 04:12:35 2024-01-01 10:30:00
## 2 2024-04-01 14:52:20 2024-04-02 10:30:00
## 3 2024-03-18 23:43:56 2024-03-19 10:30:00
© www.soinside.com 2019 - 2024. All rights reserved.