You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用dplyr和lubridate按时分筛选每日9:00-20:15时段数据

Filter Data for Daily Fixed Time Window (9:00-20:15) with dplyr & lubridate

Hey there! I get that you've already dug into filtering by hour alone, but need to narrow it down to a specific daily time window (9:00 AM to 8:15 PM) regardless of the date. Let's tackle this with dplyr and lubridate—here are two reliable approaches that'll get you what you need:

Step 1: Ensure Your Timestamp is a Datetime Type

First up, make sure your timestamp column is formatted as a datetime object (not a plain character string). For your example data (month/day/year hour:minute format), use lubridate's mdy_hm() function to convert it:

library(dplyr)
library(lubridate)

# Convert timestamp from character to datetime
df <- df %>%
  mutate(timestamp = mdy_hm(timestamp))

Step 2: Filter for the Target Time Window

Approach 1: Compare Pure Time Values (Simplest)

Use hms::as_hms() to strip away the date component and get just the time portion of your datetime. Then compare this directly to your start and end times:

df_filtered <- df %>%
  filter(
    hms::as_hms(timestamp) >= hms::as_hms("09:00:00"),
    hms::as_hms(timestamp) <= hms::as_hms("20:15:00")
  )

This method is clean and straightforward—since we're only comparing the time part, it works seamlessly across all dates in your dataset.

Approach 2: Break Down Hour & Minute (More Flexible)

If you need more control (like adjusting minute thresholds later), use lubridate's hour() and minute() functions to build explicit logical conditions:

df_filtered <- df %>%
  filter(
    # Keep times after 9:00 AM
    (hour(timestamp) > 9) | 
    (hour(timestamp) == 9 & minute(timestamp) >= 0) |
    # AND keep times before/at 8:15 PM
    (hour(timestamp) < 20) |
    (hour(timestamp) == 20 & minute(timestamp) <= 15)
  )

This logic clearly checks:

  • Any time after 9 AM, or exactly 9 AM and beyond the 0th minute
  • Any time before 8 PM, or exactly 8 PM and up to the 15th minute

Verify the Result

For your sample data, the filtered output will exclude the 8:45 AM entry and keep all rows from 9:00 AM onward (up to 20:15 PM if those times exist in your full dataset).

内容的提问来源于stack exchange,提问作者longlivebrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:30:54