Home > Net >  Convert "POSIXct" "POSIXt" class to 4 digit military time character
Convert "POSIXct" "POSIXt" class to 4 digit military time character

Time:06-08

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"

CodePudding user response:

Times that are already parsed as (or constructed) as POSIXt objects, ie Datetime objects can be formatted. Use for example

df$mltime <- strftime(df$time, "%H%M")  

to add such a column to the data.frame yielding

$ Rscript answer.R 
                 time mltime
1 1899-12-31 00:00:00   0000
2 1899-12-31 00:15:00   0015
3 1899-12-31 00:30:00   0030
4 1899-12-31 00:45:00   0045
5 1899-12-31 01:00:00   0100
6 1899-12-31 01:15:00   0115
$  

Code

df <- data.frame(time = as.POSIXct(c("1899-12-31 00:00:00 UTC", 
                                     "1899-12-31 00:15:00 UTC",
                                     "1899-12-31 00:30:00 UTC",
                                     "1899-12-31 00:45:00 UTC",
                                     "1899-12-31 01:00:00 UTC", 
                                     "1899-12-31 01:15:00 UTC")))

df$mltime <- strftime(df$time, "%H%M") 
print(df) 

CodePudding user response:

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]))
})

  • Related