r Check if Sys.time() is in a given interval of hours of the day

Viewed 425

I'm looking for a potentially less hacky solution with lubridate (sth. similar) here.

Use case: I'd like to check if Sys.time() is in between a given interval of hours, which has turned out to be a little more complex than I thought b/c a datetime seems to always need a date, e.g. paste("01-01-01", "9:00 AM")

So here is what I did to check if Sys.time() is in between working hours. I'm extracting the numerical values for the hours and comparing them, which seems hacky to me :)

as.numeric(format(lubridate::as_datetime(Sys.time(), tz = "America/New_York"), format = "%H")) >= as.numeric(format(ymd_hm(paste("01-01-01", "9:00 AM"), tz = "America/New_York"), format = "%H")) &

as.numeric(format(lubridate::as_datetime(Sys.time(), tz = "America/New_York"), format = "%H")) < as.numeric(format(ymd_hm(paste("01-01-01", "6:00 PM"), tz = "America/New_York"), format = "%H"))

This works and returns TRUE or FALSE depending on the set parameters. Again, I'm looking for a more elegant solution to this monstrosity, or maybe this helps somebody who was looking exactly for this.

Any feedback welcome!

1 Answers

You may use hour. Identical tz= on both LHS and RHS cancel out each other.

hour(Sys.time()) %in% 9:18 
# [1] FALSE
Related