Extract time (HMS) from lubridate date time object?

只愿长相守 提交于 2019-12-10 19:43:51

问题


I have the following datetime:

t <- "2018-05-01 23:02:50 UTC"

I want to split it to time and date.

When I apply date(t) I get the date part. But when I use lubridate's hms, parse_date_time and other functions to do this in "HMS" order I get NA.

I have checked other answers here on SOF but for some reason it gives me NA.

Please advise how to extract it.

I want to understand why:

strftime(t, format="%H:%M:%S") 

will do the job but what I am missing in lubridate::hms or parse_date_time?


回答1:


My solution is to install library(anytime):

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



回答2:


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:

pacman::p_load(tidyverse, 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).




回答3:


Something like this?

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


来源:https://stackoverflow.com/questions/50736661/extract-time-hms-from-lubridate-date-time-object

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