0

I can convert to POSIXct most of the time like for instance:

as.POSIXct( "20:16:32", format = "%H:%M:%S" )
[1] "2017-06-23 20:16:32 EDT"

But once the time goes beyond 24h, it fails:

as.POSIXct( "24:16:32", format = "%H:%M:%S" )
[1] NA

Which makes some sense as 24:16:32 should rather be read as 00:16:32

Such standards of 24+ are however well spread in the design of public transportation. I could of course replace all "24:" by "00:", but I am sure there is a more elegant way out.

Xavier Prudent
  • 1,570
  • 3
  • 25
  • 54

1 Answers1

0

Read the time string into a data frame dd and set next_day to 1 if the hour exceeds 24 or more or 0 if not. Subtract 24 from the hour if next_day is 1 and add 1 day's worth of seconds. Given that today is June 23, 2017 this would work for hours between 0 and 47.

x <- "24:16:32" # test input

dd <- read.table(text = x, sep = ":", col.names = c("hh", "mm", "ss"))
next_day <- dd$hh >= 24
s <- sprintf("%s %0d:%0d:%0d", Sys.Date(), dd$hh - 24 * next_day, dd$mm, dd$ss)
as.POSIXct(s) + next_day * 24 * 60 * 60
##  "2017-06-24 00:16:32 EDT"
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341