I get time now by time_now <- str_split(date(), " ")[[1]][5] %>% hms()
and want to find its exist in time 08:00:00
until 09:49:20
. how can do it?
If what you are trying to check is if the time right now is between 08:00:00
and 09:49:20
you can try this:
Sys.time() %within% interval(Sys.Date() + hours(8), Sys.Date() + hours(9) + minutes(49) + seconds(20))
thanks for help.
no i want to get time now and computed it , that is in specific interval or no.
within
in lubridate
works as well.
https://www.rdocumentation.org/packages/lubridate/versions/1.7.4/topics/%within%
i get this error
int <- interval(hms("09:00:00"), hms("12:30:00"))
Error in as.POSIXct.numeric(x, tz = tz) : 'origin' must be supplied
I think you need the date as well. e.g.:
> int <- interval(ymd_hms("2001-01-01 09:00:00"), (ymd_hms("2001-01-01 12:30:00")))
> int
[1] 2001-01-01 09:00:00 UTC--2001-01-01 12:30:00 UTC
> ymd_hms("2001-01-01 09:15:00") %within% int
[1] TRUE
> ymd_hms("2001-01-01 12:45:00") %within% int
[1] FALSE
I can't use only hms? Because i want to tun for every day
I have only used it with dates, but I imagine that you could put it in to a function where you strip out the date then use it to calculate the interval.
Maybe something like this:
library(lubridate)
library(glue)
df <- tibble(datetime = c(ymd_hms("2020-02-10 09:00:00"), ymd_hms("2020-02-11 13:00:00")))
# A tibble: 2 x 1
datetime
<dttm>
1 2020-02-10 09:00:00
2 2020-02-11 13:00:00
df %>%
mutate(date = date(datetime)) %>%
mutate(int2 = interval(ymd_hms(glue("{date} 08:00:00")), ymd_hms(glue("{date} 12:00:00")))) %>%
mutate(within_int = if_else(datetime %within% int2, "yes", "no"))
# A tibble: 2 x 4
datetime date int2 within_int
<dttm> <date> <Interval> <chr>
1 2020-02-10 09:00:00 2020-02-10 2020-02-10 08:00:00 UTC--2020-02-10 12:00:00 UTC yes
2 2020-02-11 13:00:00 2020-02-11 2020-02-11 08:00:00 UTC--2020-02-11 12:00:00 UTC no
thanks for help.
what is this format date?
> date()
[1] "Mon Feb 10 15:06:48 2020"
in this code Sys.time()
give me tz = "+0330"
and interval part give tz = "UTC"
, and return False
. i use Sys.setenv(tz = "+0330")
but don't work!
in the interval
function you can set a parameter tzone
. Looks like "+0330" is Iran.
> interval(Sys.Date() + hours(8), Sys.Date() + hours(9) + minutes(49) + seconds(20), tzone = "GMT")
[1] 2020-02-10 08:00:00 GMT--2020-02-10 09:49:20 GMT
> interval(Sys.Date() + hours(8), Sys.Date() + hours(9) + minutes(49) + seconds(20), tzone = "America/Los_Angeles")
[1] 2020-02-10 08:00:00 PST--2020-02-10 09:49:20 PST
> interval(Sys.Date() + hours(8), Sys.Date() + hours(9) + minutes(49) + seconds(20), tzone = "Iran")
[1] 2020-02-10 08:00:00 +0330--2020-02-10 09:49:20 +0330