I have a local time like \"2013-08-27 10:01:22\"
, how do I convert it to epoch time?
basically I need the opposite of as.POSIXct
, I searched on
You can use as.integer
to get seconds since epoch began...
x <- as.POSIXct( Sys.time() )
#[1] "2013-08-27 12:37:17 BST"
class(x)
#[1] "POSIXct" "POSIXt"
as.integer( x )
#[1] 1377603437
Using a vector of strings called times
:
times
#[1] "2013-08-27 12:39:32" "2013-08-27 12:39:33" "2013-08-27 12:39:34"
#[4] "2013-08-27 12:39:35" "2013-08-27 12:39:36" "2013-08-27 12:39:37"
#[7] "2013-08-27 12:39:38" "2013-08-27 12:39:39" "2013-08-27 12:39:40"
#[10] "2013-08-27 12:39:41"
as.integer( as.POSIXct( times ) )
#[1] 1377603609 1377603610 1377603611 1377603612 1377603613 1377603614
#[7] 1377603615 1377603616 1377603617 1377603618
Without the timezone in the strings you will probably have to specify the tz
argument to as.POSIXct
, e.g. as.integer( as.POSIXct( times ) , tz = "BST" )
for British Summertime.
The accepted answer truncates time to the whole second. POSIXct
actually provides sub-second resolution, though. As mentioned in the comments by “statquant”, you can use as.numeric
to obtain the exact epoch:
result = as.numeric(as.POSIXct(Sys.time()))
Beware that with the default options for digit display in R this will look like it has no digits behind the decimal point:
> result
[1] 1480599768
However, these are simply truncated in the display. To make them visible, use:
> dput(result)
1480599767.58447
… or set options('digits')
to a higher value.
we can also use
unclass(Sys.time())