R - 以毫秒为单位获取当前时间

Sja*_*sma 13 r

我正在尝试进行API调用,这需要一个毫秒的时间.我是R的新手,并且谷歌搜索了几个小时,以实现像Java一样的东西:

System.currentTimeMillis();
Run Code Online (Sandbox Code Playgroud)

我看到的只有像

Sys.Date()Sys.time

返回格式化日期而不是毫秒时间.

我希望有人可以给我一个解决我问题的oneliner.

Jos*_*ich 27

Sys.time不会返回"格式化时间".它返回一个POSIXct被分类的对象,这是自Unix时代以来的秒数.当然,当您打印该对象时,它会返回格式化的时间.但是打印的东西不是它的本质.

要以毫秒为单位获取当前时间,您只需将输出转换Sys.time为数字,然后乘以1000即可.

R> print(as.numeric(Sys.time())*1000, digits=15)
[1] 1476538955719.77
Run Code Online (Sandbox Code Playgroud)

根据您要进行的API调用,您可能需要删除小数毫秒.

  • 对于懒惰的人(删除小数毫秒): current_timestamp = round(as.numeric(Sys.time())*1000) (2认同)

Mau*_*ers 6

无需设置全局变量digits.secs.详情strptime请见.

# Print milliseconds of current time
# See ?strptime for details, specifically
# the formatting option %OSn, where 0 <= n <= 6 
as.numeric(format(Sys.time(), "%OS3")) * 1000
Run Code Online (Sandbox Code Playgroud)