如何将格式化的本地时间转换为纪元?

swa*_*ang 16 r

我有一个当地时间"2013-08-27 10:01:22",如何将其转换为纪元时间?

基本上我需要相反的as.POSIXct,我搜索谷歌,令人惊讶的是没有找到任何.

Sim*_*lon 27

as.integer从纪元开始以来,您可以使用秒数...

x <- as.POSIXct( Sys.time() )
#[1] "2013-08-27 12:37:17 BST"

class(x)
#[1] "POSIXct" "POSIXt" 

as.integer( x )
#[1] 1377603437
Run Code Online (Sandbox Code Playgroud)

使用一个名为的字符串向量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
Run Code Online (Sandbox Code Playgroud)

如果没有字符串中的时区,您可能必须指定tz参数as.POSIXct,例如as.integer( as.POSIXct( times ) , tz = "BST" )英国夏令时.

  • 如果您有亚秒级分辨率,则需要使用`as.numeric`而不是`as.integer`作为sub-second存储为秒的十进制 (2认同)
  • @swang就像我说的子毫米`x < - as.POSIXct('2012-06-01 12:32:12.123')``as.numeric(x)`会给你`1338546732.123`(小心`选项(数字)`它需要足够大) (2认同)

Kon*_*lph 6

接受的答案会缩短整秒的时间.POSIXct但实际上提供了亚秒级分辨率.正如"statquant"的评论中所提到的,您可以使用as.numeric获取确切的时期:

result = as.numeric(as.POSIXct(Sys.time()))
Run Code Online (Sandbox Code Playgroud)

请注意,使用R中数字显示的默认选项,它看起来像小数点后面没有数字:

> result
[1] 1480599768
Run Code Online (Sandbox Code Playgroud)

但是,这些只是在显示屏中被截断.要使它们可见,请使用:

> dput(result)
1480599767.58447
Run Code Online (Sandbox Code Playgroud)

...或设置options('digits')为更高的值.