Converting time format to numeric with R

Based on the revised question this should do what you want:

begin <- "2001-03-13 10:31:00"
as.numeric(as.POSIXct(begin))

The result is a unix timestamp, the number of seconds since epoch, assuming the timestamp is in the local time zone.


The example from ?as.POSIX help gives

as.POSIXct(strptime(begin, "%Y-%m-%d %H:%M:%S"))

so for you it would be

as.numeric(as.POSIXct(strptime(begin, "%Y-%m-%d %H:%M:%S")))

Maybe this could also work:

library(lubridate)
...
df <- '24:00:00'

as.numeric(hms(df))

hms() will convert your data from one time format into another, this will let you convert it into seconds. See full documentation.

I tried this because i had trouble with data which was in that format but over 24 hours.


If you just want to remove ":" , " ", and "-" from a character vector then this will suffice:

end <- gsub("[: -]", "" , begin, perl=TRUE)
#> end
#[1] "20010313103100"

You should read the section about 1/4 of the way down in ?regex about character classes. Since the "-" is special in that context as a range operator, it needs to be placed first or last.

After your edit then the answer is clearly what @joran wrote, except that you would need first to convert to a DateTime class:

 as.numeric(as.POSIXct(begin))
#[1] 984497460

The other point to make is that comparison operators do work for Date and DateTime classed variables, so the conversion may not be necessary at all. This compares 'begin' to a time one second later and correctly reports that begin is earlier:

as.POSIXct(begin) < as.POSIXct(begin) +1
 #[1] TRUE