Search code examples
rdatetimelubridate

How to extract time from lubridate?


I want to extract a day-, month-, hour- and minute-vector from a vector of the type factor of the format "DD-M-YYYY HH:MM" (e.g. "14-3-2018 00:34").

Using Lubridate, the month and day are retrieved as expected, but when I try to retrieve the hour and the minute, it returns all zero's.

I've tried the following:

dataset$Month = month(dataset$msgDateTime)
dataset$Day = day(dataset$msgDateTime)
dataset$Hour = hour(dataset$msgDateTime)
dataset$Minute = minute(dataset$msgDateTime)

And so the first two lines yielded the results I wanted, but the last two lines only resulted in zero's.

How can I get this to work?


Solution

  • Here's a solution using lubridate:

    library(lubridate)
    library(dplyr)
    
    factor_datetime <- factor("14-3-2018 00:34")
    
    tibble(
      full_datetime = lubridate::dmy_hm(
        factor_datetime,
        quiet = FALSE,
        tz = "UTC",
        locale = Sys.getlocale("LC_TIME"),
        truncated = 0
      )) %>%
      mutate(Month = lubridate::month(full_datetime),
             Day = lubridate::day(full_datetime),
             Hour = lubridate::hour(full_datetime),
             Minute = lubridate::minute(full_datetime))
    
    # A tibble: 1 x 5
    # full_datetime        Month   Day  Hour Minute
    # <dttm>               <dbl> <int> <int>  <int>
    # 2018-03-14 00:34:00      3    14     0     34