how to filter a timestamp by time of day?

Hello there,

This is an old issue, but surprisingly the last version of lubridate does not seem to handle this very well.
Consider this simple example

dataframe <- tibble(gmt_time = c('2016-07-08 04:30:10.690'), value = c(1))

library(hms)
library(lubridate)

dataframe %>% 
  mutate(gmt_time = ymd_hms(gmt_time),
         est_time = with_tz(gmt_time, 'America/New_York'),
         myhour1 = as.hms(est_time),
         myhour2 = as.hms(gmt_time))

# A tibble: 1 x 5
  gmt_time                value est_time                myhour1       myhour2      
  <dttm>                  <dbl> <dttm>                  <time>        <time>       
1 2016-07-08 04:30:10.690     1 2016-07-08 00:30:10.690 30'10.690000" 30'10.690000"

What is going on here? I would like to extract the time component of the timestamp, so that I can run filters like time > 04:30:00

Thanks!

as.hms() is not a lubridate function but a hms function, when you use as.hms() this way, you have to specify the time zone, like this.

library(dplyr)
library(hms)
library(lubridate)

dataframe <- tibble(gmt_time = c('2016-07-08 04:30:10.690'), value = c(1))

dataframe %>% 
    mutate(gmt_time = ymd_hms(gmt_time),
           est_time = with_tz(gmt_time, 'America/New_York'),
           myhour1 = as.hms(est_time, tz = 'UTC'),
           myhour2 = as.hms(gmt_time, tz = 'America/New_York'))
#> # A tibble: 1 x 5
#>   gmt_time            value est_time            myhour1      myhour2      
#>   <dttm>              <dbl> <dttm>              <time>       <time>       
#> 1 2016-07-08 04:30:10     1 2016-07-08 00:30:10 04:30.690000 30'10.690000"

Created on 2019-01-18 by the reprex package (v0.2.1)

1 Like

Thanks! that is very nice. Its a lot of tz repetition but that seems to be working correctly

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'))

gives

# 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

You can set the defaul time zone with this pkgconfig::set_config("hms::default_tz", "UTC")

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.