How to Read, Display, and Compute Milliseconds in R using readr and lubridate
Understanding the Problem: Parsing Milliseconds and AM/PM in R
When dealing with high-precision timestamp data in R—such as scientific experiments or event logs—you often need to read and compute differences down to the millisecond. A common issue occurs when attempting to parse 12-hour timestamps with fractional seconds and AM/PM indicators (e.g., 03:44:43.300 PM) using readr::parse_time() or col_time().
By default, readr relies on the hms package for time-only columns. hms objects represent time differences from midnight and do not handle 12-hour clock notations (%I and %p) combined with fractional seconds (%OS) reliably. To resolve this, the best approach is to combine the date and time strings and parse them into R's native POSIXct date-time format using lubridate.
Step 1: Enable Millisecond Display in R
By default, R suppresses fractional seconds when printing date-time objects to the console. To ensure R displays milliseconds, set the digits.secs option at the beginning of your script: