R:如何按小时和分钟过滤时间戳? [英] R: how to filter a timestamp by hour and minute?
本文介绍了R:如何按小时和分钟过滤时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在下面的例子中苦苦挣扎
I am struggling with the following example
time = c('2013-01-03 21:59:21.549', '2013-01-04 22:00:21.549', '2013-01-05 22:01:21.222', '2013-01-06 22:06:23.559' )
value = c(1,2,3,4)
data <- data_frame(time, value)
data <-data %>% mutate(time = ymd_hms(time))
> data
# A tibble: 4 × 2
time value
<dttm> <dbl>
1 2013-01-03 21:59:21 1
2 2013-01-04 22:00:21 2
3 2013-01-05 22:01:21 3
4 2013-01-06 22:06:23 4
除了每天只在21:59
和22:01
(包括)之间保持观察之外,我怎么写dplyr::filter
语句?
How can I write a dplyr::filter
statement than only keeps observations between 21:59
and 22:01
(included) every day?
分别使用hour(time)
和minute(time)
玩似乎不太好.
Playing separately with hour(time)
and minute(time)
does not seem to work very well here.
我在这里想念东西吗?
预期输出:仅第1,2和3行. 谢谢!
Output expected: row 1,2 and 3 only. Thanks!
推荐答案
2019在这里!
这是使用as.hms
的更好(更简单)的解决方案. tz
参数是强制性的.
2019 is here!
Here is a better (and simpler) solution using as.hms
. The tz
argument is mandatory.
time_str = c('2013-01-03 21:59:21.549', '2013-01-04 22:00:21.549', '2013-01-05
22:01:21.222', '2013-01-06 22:06:23.559' )
value = c(1,2,3,4)
data <- tibble(time_str, value)
data %>% mutate(timestamp_utc = ymd_hms(time_str, tz = 'UTC'),
timestamp_est = with_tz(timestamp_utc, 'America/New_York'),
time_est = as.hms(timestamp_est, tz = 'America/New_York')) %>%
filter(time_est >= hms::as.hms('16:59:00', tz = 'America/New_York'),
time_est <= hms::as.hms('17:01:00', tz = 'America/New_York'))
会做
# A tibble: 2 x 5
time_str value timestamp_utc timestamp_est time_est
<chr> <dbl> <dttm> <dttm> <time>
1 2013-01-03 21:59:21.549 1 2013-01-03 21:59:21.549 2013-01-03 16:59:21.549 16:59.549
2 2013-01-04 22:00:21.549 2 2013-01-04 22:00:21.549 2013-01-04 17:00:21.549 17:00.549
这篇关于R:如何按小时和分钟过滤时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文