Extract time (HMS) from lubridate date time object?

Something like this?

  library(hms)
    t <- "2018-05-01 23:02:50 UTC"
    unlist(strsplit(t," "))[2]%>%hms::parse_hms()

What you are missing in lubridate's hms() is that it expects "a character vector of hour minute second triples" as an argument. There's no provision for handling a string which also contains date info. Hence, the output of Sys.Date() or lubridate::now() doesn't work as input to lubridate::hms().

In case you want a tidyverse solution, here's one:

library(tidyverse)
library(lubridate)

now()
#> [1] "2018-08-13 16:41:31 BST"

get_time <- function(time = now()) {
  time %>%
    str_split(" ") %>%
    map_chr(2) %>%
    hms()
}

get_time()
#> [1] "16H 41M 31S"

get_time("2018-05-01 23:02:50 UTC")
#> [1] "23H 2M 50S"

Created on 2018-08-13 by the reprex package (v0.2.0).


Is this what you were looking for? It can now be done more simply with hms::as_hms.

> library(lubridate)
> library(hms)
> as_hms(ymd_hms("2018-05-01 23:02:50 UTC"))
23:02:50

> t <- "2018-05-01 23:02:50 UTC"
> as_hms(ymd_hms(t))
23:02:50

My solution is to install library(anytime):

date <- anytime::anydate(t)
time <- strftime(t, format="%H:%M:%S")

Tags:

Date

R

Lubridate