Determine if 24 hour datetime is within interval

☆樱花仙子☆ 提交于 2019-12-02 02:57:57

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!