Print Time with Milliseconds in R (Example)

 

In this tutorial you’ll learn how to return a time object with milliseconds in R.

The tutorial consists of these topics:

Let’s dig in:

 

Creation of Example Data

First, we’ll have to create some data that we can use in the following examples:

my_time <- "2020-10-10 10:15:20.111"       # Create character string containing time
my_time                                    # Print character string
# "2020-10-10 10:15:20.111"

As you can see based on the previous output of the RStudio console, our example data is a character string containing a specific date and time.

 

Example: Convert Character to Time with Milliseconds

This Example explains how to convert our character string to a time object showing milliseconds. Generally speaking, we can use the strptime function to convert character strings to time objects:

strptime(my_time, "%Y-%m-%d %H:%M:%OS")    # Convert to time without milliseconds
# "2020-10-10 10:15:20 CEST"

However, as you can see based on the previous output of the RStudio console, our converted time is not showing the milliseconds of our original character string.

In case we want to show milliseconds, we can change the global options of RStudio to show more digits. Make sure to also save the original global options so that you can set it back later:

my_options <- options(digits.secs = 3)     # Modify and save default global options

Now, we can apply the strptime function exactly the same way as we did before:

strptime(my_time, "%Y-%m-%d %H:%M:%OS")    # Time with milliseconds
# "2020-10-10 10:15:20.111 CEST"

This time, the milliseconds are also printed to the RStudio console. Looks good!

Make sure to set back the options to the options you used before:

options(my_options)                        # Set global options back to default

You can check if it worked by running exactly the same strptime code again:

strptime(my_time, "%Y-%m-%d %H:%M:%OS")    # Time without milliseconds
# "2020-10-10 10:15:20 CEST"

This time the milliseconds are not shown anymore.

 

Video, Further Resources & Summary

Have a look at the following video of my YouTube channel. I show the R programming code of this page in the video:

 

The YouTube video will be added soon.

 

In addition, you may want to have a look at some of the related articles of this website:

 

To summarize: You learned in this article how to parse milliseconds in R programming. If you have additional questions, let me know in the comments.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top