问题
Hope you can help. Have a dataframe with date times in it. I'd like to determine if the time result occurs after hours (> 16:00). Is there an easy way to do this? Was planning on converting the time to seconds and then doing like this but suppose there's an easier way to do this via R.
datetimes <- c("2013-04-01 08:19:00", "2013-04-02 16:19:00", "2017-02-17 14:01:00", "2017-02-17 22:01:00")
as.POSIXct(datetimes)
回答1:
Just use a format
and comparsion via >=
:
format(datetimes,"%H") >= 16
#[1] FALSE TRUE FALSE TRUE
Assuming you have already converted via as.POSIXct()
as shown in your question.
Even though format
returns a character string, the comparison is safe to do with a numeric as all the single digit values are padded like "08"
回答2:
The lubridate package makes this really easy. See https://cran.r-project.org/web/packages/lubridate/vignettes/lubridate.html for more info.
library(lubridate)
hour(as.POSIXct(datetimes))>16
来源:https://stackoverflow.com/questions/42378533/determine-if-24-hour-datetime-is-within-interval