1
durations <- "01:01:01" #1 hour 1 min and 1 sec

How can I use base R to get the numeric 10-base representation of the seconds (or minutes) this corresponds to (it would be 3661 seconds) ?. Time (and dates) in R always hurts me. There are plenty of similar SO questions (e.g. here and here) but I still did not really get it right. One try was:

as.numeric(format(strptime('00:01:01', format='%H:%M:%S'), '%S'))
Jaap
  • 81,064
  • 34
  • 182
  • 193
user3375672
  • 3,728
  • 9
  • 41
  • 70
  • 1
    this one has a nice answer https://stackoverflow.com/questions/10835908/is-there-a-way-to-convert-mmss-00-to-seconds-00-in-r – timfaber Apr 26 '18 at 10:46

2 Answers2

1

After we convert it to POSIXlt, extract the hour, min and sec and do the arithmetic

v1 <- strptime(durations, format='%H:%M:%S')
v1$hour * 3600 + v1$min * 60 + v1$sec
#[1] 3661

Or

c(unlist(unclass(v1)[c("hour", "min", "sec")]) %*% c(3600, 60, 1))
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Quick and dirty:

as.numeric(strsplit(durations, ":")[[1]]) %*% c(3600, 60, 1)
rinni
  • 2,246
  • 1
  • 18
  • 21