3

How can i label time of the day (Morning, Afternoon and Evening) for given timestamps?

Initial Data

Id            Time_stamp
3083188c     2016-08-29 13:10:51
924d500e     2016-08-29 09:22:33
ad4dd7ff     2016-08-25 20:29:35

Final data

 Id            Time_stamp              Time_of_day
3083188c     2016-08-29 13:10:51        Afternoon
924d500e     2016-08-29 09:22:33        Morning
ad4dd7ff     2016-08-25 20:29:35        Evening
Community
  • 1
  • 1
ajax
  • 131
  • 1
  • 11

1 Answers1

8

You can achieve this with lubridate and cut.

library(lubridate)

# transform into date time column (if it is not already one)
df$Time_stamp <- ymd_hms(df$Time_stamp)

# create breaks
breaks <- hour(hm("00:00", "6:00", "12:00", "18:00", "23:59"))
# labels for the breaks
labels <- c("Night", "Morning", "Afternoon", "Evening")

df$Time_of_day <- cut(x=hour(df$Time_stamp), breaks = breaks, labels = labels, include.lowest=TRUE)

df

        Id          Time_stamp Time_of_day
1 3083188c 2016-08-29 13:10:51   Afternoon
2 924d500e 2016-08-29 09:22:33     Morning
3 ad4dd7ff 2016-08-25 20:29:35     Evening

data:

df <- structure(list(Id = c("3083188c", "924d500e", "ad4dd7ff"), 
                     Time_stamp = c("2016-08-29 13:10:51", "2016-08-29 09:22:33", "2016-08-25 20:29:35")), 
                .Names = c("Id","Time_stamp"),
                class = "data.frame", 
                row.names = c(NA, -3L))
phiver
  • 23,048
  • 14
  • 44
  • 56