Date time conversion and extract only time

前端 未结 5 911
暖寄归人
暖寄归人 2020-12-09 08:36

Want to change the class for Time to POSIXlt and extract only the hours minutes and seconds

str(df3$Time)
chr [1:2075259] \"17:24:00\" \"17:25:00\" \"17:26:0         


        
5条回答
  •  既然无缘
    2020-12-09 09:25

    This is my idiom for getting just the timepart from a datetime object. I use floor_date() from lubridate to get midnight of the timestamp and take the difference of the timestamp and midnight of that day. I create and store a hms object provided with lubridate (I believe) in dataframes because the class has formatting of hh:mm:ss that is easy to read, but the underlying value is a numeric value of seconds. Here is my code:

    library(tidyverse)
    library(lubridate)
    #> 
    #> Attaching package: 'lubridate'
    #> The following object is masked from 'package:base':
    #> 
    #>     date
    
    # Create timestamps
    #
    # Get timepart by subtacting the timestamp from it's floor'ed date, make sure
    # you convert to seconds, and then cast to a time object provided by the
    # `hms` package.
    # See: https://www.rdocumentation.org/packages/hms/versions/0.4.2/topics/hms
    dt <- tibble(dt=c("2019-02-15T13:15:00", "2019-02-19T01:10:33") %>% ymd_hms()) %>%
      mutate(timepart = hms::hms(as.numeric(dt - floor_date(dt, "1 day"), unit="secs")))
    
    # Look at result
    print(dt)
    #> # A tibble: 2 x 2
    #>   dt                  timepart
    #>                 

    Created on 2019-02-15 by the reprex package (v0.2.1)

提交回复
热议问题