Extract time from timestamp?

前端 未结 4 578
闹比i
闹比i 2020-12-11 17:28

Essentially, I want only the hour, minute, and seconds from a column of timestamps I have in R, because I want to view how often different data points occur throughout diffe

相关标签:
4条回答
  • 2020-12-11 18:14

    We can use strptime to convert to a datetime class and then format to extract the hour:min:sec.

    dtime <- strptime(str1, "%Y-%m-%dT%H:%M:%SZ")
    format(dtime, "%H:%M:%S")
    #[1] "17:07:36"
    

    If the OP wants to have the hour, min, sec as separate columns

    read.table(text=format(dtime, "%H:%M:%S"), sep=":", header=FALSE)
    #  V1 V2 V3
    #1 17  7 36
    

    Another option is using lubridate

    library(lubridate)
    format(ymd_hms(str1), "%H:%M:%S")
    #[1] "17:07:36"
    

    data

    str1 <- "2008-08-07T17:07:36Z"
    
    0 讨论(0)
  • 2020-12-11 18:14

    I think you are expecting this...

    Sys.time()
    [1] "2016-04-19 11:09:30 IST"
    format(Sys.time(),format = '%T')
    [1] "11:09:30"
    

    if you want to give your own timestamp, then use bellow code:

    format(as.POSIXlt("2016-04-19 11:02:22 IST"),format = '%T')
    [1] "11:02:22"
    
    0 讨论(0)
  • 2020-12-11 18:18

    Just

    x <- '2008-08-07T17:07:36Z'
    substr(x, 12, 19)
    #[1] "17:07:36"
    

    ...will do it if the timestamp is consistent, which I imagine it would be given it is an ISO_8601 ( https://en.wikipedia.org/wiki/ISO_8601 ) string.

    0 讨论(0)
  • 2020-12-11 18:27

    A regular expression will probably be quite efficient for this:

    x <- '2008-08-07T17:07:36Z'
    x
    ## [1] "2008-08-07T17:07:36Z"
    sub('.*T(.*)Z', '\\1', x)
    ## [1] "17:07:36"
    
    0 讨论(0)
提交回复
热议问题