Home > Software engineering >  How to Check if a POSIXct is greater than a certain time
How to Check if a POSIXct is greater than a certain time

Time:09-22

I have a data frame that contains a column "Depart". This column is POSIXct/POSIXt and has the following format : "2022-09-21 17:00:00". I am trying to create a case_when() that will check each row and return a value if the time is before 5PM.

Something like this:

time_flag_df <- my_df %>% mutate(my_column = case_when(Depart < 5pm ~ "Y" )

ideally this would mutate a new column containing my "Y" flags.

Thanks!

CodePudding user response:

There is no magic -- if the datetime object is in fact parsed and represented as a POSIXct object you just use < or <= as usual.

A self-contained two-line base R example follows. Easy enough to transcribe into data.table or dplyr syntax and preferences.

> D <- data.frame(Depart=seq(as.POSIXct("2022-09-21 00:00:00"), 
                             as.POSIXct("2022-09-22 00:00:00"), by="1 hour"))
> D <- within(D, earlier <- Depart < as.POSIXct("2022-09-21 17:00:00"))
> D
                Depart earlier
1  2022-09-21 00:00:00    TRUE
2  2022-09-21 01:00:00    TRUE
3  2022-09-21 02:00:00    TRUE
4  2022-09-21 03:00:00    TRUE
5  2022-09-21 04:00:00    TRUE
6  2022-09-21 05:00:00    TRUE
7  2022-09-21 06:00:00    TRUE
8  2022-09-21 07:00:00    TRUE
9  2022-09-21 08:00:00    TRUE
10 2022-09-21 09:00:00    TRUE
11 2022-09-21 10:00:00    TRUE
12 2022-09-21 11:00:00    TRUE
13 2022-09-21 12:00:00    TRUE
14 2022-09-21 13:00:00    TRUE
15 2022-09-21 14:00:00    TRUE
16 2022-09-21 15:00:00    TRUE
17 2022-09-21 16:00:00    TRUE
18 2022-09-21 17:00:00   FALSE
19 2022-09-21 18:00:00   FALSE
20 2022-09-21 19:00:00   FALSE
21 2022-09-21 20:00:00   FALSE
22 2022-09-21 21:00:00   FALSE
23 2022-09-21 22:00:00   FALSE
24 2022-09-21 23:00:00   FALSE
25 2022-09-22 00:00:00   FALSE
> 
  •  Tags:  
  • r
  • Related