How to convert a formatted local time to epoch?

后端 未结 3 905
渐次进展
渐次进展 2021-02-07 07:17

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

3条回答
  •  花落未央
    2021-02-07 07:59

    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.

提交回复
热议问题