Search code examples
rcharacterposixct

Convert "POSIXct" "POSIXt" class to 4 digit military time character


Is there a way to convert a datetime ("POSIXct" "POSIXt") to a 4 digit character string?

> class(df$time)
[1] "POSIXct" "POSIXt" 

> head(df$time)
[1] "1899-12-31 00:00:00 UTC" "1899-12-31 00:15:00 UTC" "1899-12-31 00:30:00 UTC"
[4] "1899-12-31 00:45:00 UTC" "1899-12-31 01:00:00 UTC" "1899-12-31 01:15:00 UTC"

to...

> head(df$time)
[1] "0000" "0015" "0030"
[4] "0045" "0100" "0115"

Solution

  • Try this

    sapply(strsplit(as.character(df$time) , " ") , function(x) {
    s <- x[[2]]
    s <- strsplit(s , ":")
    sapply(s , function(x) paste0(x[1],x[2]))
    })