按时间过滤没有日期的数据

我有一个列为“ datetime”的数据框,其中包含作为整数的数据。我想在此列中按时间过滤它,但没有日期。因此,例如,从具有这样的列的数据帧中:

2020-02-04 00:00:01
2020-03-01 00:00:02
2020-03-02 00:01:01
2020-04-06 00:00:31

我只想获取00:00:00到00:01:00之间的数据,所以:

2020-02-04 00:00:01
2020-03-01 00:00:02
2020-04-06 00:00:31

(或没有日期,过滤后,我不需要此列)

我试过使用format():

df$datetime <- format(as.POSIXct(df$datetime), format("%H:%M:%S"))

但是它将列中的每个单元格替换为00:00:00。我将不胜感激:)

评论
默默然
默默然

One approach is to extract the hours, minutes and seconds out into their own columns with lubridate. Then it's easy to filter.

library(dplyr)
library(lubridate)
data %>% 
  mutate(Hour = hour(TimeStamp),
         Minute = minute(TimeStamp),
         Second = second(TimeStamp)) %>%
  dplyr::filter(Hour == 0 & (Minute == 0 | Minute == 1 & Second == 0))
            TimeStamp Hour Minute Second
1 2020-02-04 00:00:01    0      0      1
2 2020-03-01 00:00:02    0      0      2
3 2020-04-06 00:00:31    0      0     31
点赞
评论