Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a formatted local time to epoch?

Tags:

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 google and surprisingly didn't find any.

like image 769
swang Avatar asked Aug 27 '13 11:08

swang


People also ask

How do you convert time to epoch time?

Epoch Time Difference Formula Multiply the two dates' absolute difference by 86400 to get the Epoch Time in seconds – using the example dates above, is 319080600.

How do I convert time to epoch in Excel?

Select a blank cell, suppose Cell C2, and type this formula =(C2-DATE(1970,1,1))*86400 into it and press Enter key, if you need, you can apply a range with this formula by dragging the autofill handle. Now a range of date cells have been converted to Unix timestamps.


2 Answers

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.

like image 199
Simon O'Hanlon Avatar answered Sep 22 '22 02:09

Simon O'Hanlon


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.

like image 42
Konrad Rudolph Avatar answered Sep 24 '22 02:09

Konrad Rudolph