Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current time in milliseconds

Tags:

r

I am trying to do an API call which requires a time in milliseconds. I am pretty new in R and been Googling for hours to achieve something like what In Java would be:

System.currentTimeMillis();

Only thing i see is stuff like

Sys.Date() and Sys.time

which returns a formatted date instead of time in millis.

I hope someone can give me a oneliner which solves my problem.

like image 617
Sjaak Rusma Avatar asked Oct 15 '16 13:10

Sjaak Rusma


People also ask

How do you convert datetime to milliseconds?

Use the Date() constructor to convert milliseconds to a date, e.g. const date = new Date(timestamp) . The Date() constructor takes an integer value that represents the number of milliseconds since January 1, 1970, 00:00:00 UTC and returns a Date object.

How do you convert UTC time to milliseconds?

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); format. setTimeZone(TimeZone. getTimeZone("UTC")); Date date = format. parse(text); long millis = date.

How do you find milliseconds from a date?

Once you have the Date object, you can get the milliseconds since the epoch by calling Date. getTime() . The full example: String myDate = "2014/10/29 18:10:45"; //creates a formatter that parses the date in the given format SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = sdf.


3 Answers

Sys.time does not return a "formatted time". It returns a POSIXct classed object, which is the number of seconds since the Unix epoch. Of course, when you print that object, it returns a formatted time. But how something prints is not what it is.

To get the current time in milliseconds, you just need to convert the output of Sys.time to numeric, and multiply by 1000.

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

Depending on the API call you want to make, you might need to remove the fractional milliseconds.

like image 175
Joshua Ulrich Avatar answered Oct 20 '22 05:10

Joshua Ulrich


No need for setting the global variable digits.secs. See strptime for details.

# 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
like image 26
Maurits Evers Avatar answered Oct 20 '22 03:10

Maurits Evers


To get current epoch time (in second):

as.numeric(Sys.time())

If you want to get the time difference (for computing duration for example), just subtract Sys.time() directly and you will get nicely formatted string:

currentTs <- Sys.time()
# about five seconds later
elapsed <- Sys.time() - currentTs
print(elapsed)    # Time difference of 4.926194 secs
like image 35
cakraww Avatar answered Oct 20 '22 05:10

cakraww