r-lib/clock

Add an FAQ entry for "No but really, I want POSIXct subseconds"

Opened this issue · 0 comments

After

## Where did my POSIXct subseconds go?

Using this as an example
r-dbi/bigrquery#591 (comment)

bq_datetime_parse <- function(x) {
  # `format` matches clock already.
  # Bigquery DATETIME is documented as microsecond precision.
  # https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#datetime_type
  x <- clock::year_month_day_parse(x, precision = "microsecond")
  
  # Manually retain microseconds for the POSIXct
  microseconds <- clock::get_microsecond(x)
  microseconds <- microseconds / 1000000
  
  # Convert to POSIXct at second precision since that is what clock asserts
  # the precision of a POSIXct is. Can use sys-time since we are going straight
  # to UTC.
  x <- clock::calendar_narrow(x, "second")
  x <- clock::as_sys_time(x)
  x <- as.POSIXct(x, tz = "UTC")
  
  # Manually add microseconds back on (lossy, floating point issues!)
  x <- x + microseconds
  
  x
}