Search code examples
rdata.tablenanotime

how to convert a nanotime to character?


Consider this simple example

DT <- data.table::data.table(mytime =  c(nanotime('2011-12-05 08:30:00.000',format ="%Y-%m-%d %H:%M:%E9S",  tz ="GMT"),
                         nanotime('2011-12-05 08:30:00.100',format ="%Y-%m-%d %H:%M:%E9S",  tz ="GMT"),
                         nanotime('2011-12-05 08:30:00.825',format ="%Y-%m-%d %H:%M:%E9S",  tz ="GMT")))
#convert the timestamp to string
DT[, mytime_character := strftime(mytime, format = '%Y-%m-%d %H:%M:%OS3')]

> DT
                                mytime        mytime_character
1: 2011-12-05T08:30:00.000000000+00:00 2011-12-05 03:30:00.000
2: 2011-12-05T08:30:00.100000000+00:00 2011-12-05 03:30:00.099
3: 2011-12-05T08:30:00.825000000+00:00 2011-12-05 03:30:00.825

As you can see, converting the nanotime timestamp to character (using strftime) creates a wrong millisecond part for the second timestamp: .099 instead of .100

Unfortunately, I need to convert my timestamps to string so that they can be ingested by other programming languages.

Is there a way to convert the timestamps properly to character without precision loss?

Thanks!


Solution

  • You are having an elementary misunderstanding here.

    We use nanotime because the standard time formats in R only have (not-quite) microsecond resolution. So you, by using strftime() on it, are doing it wrong.

    But nanotime, being a proper package, of course has a format() method:

    R> DT <- data.table::data.table(mt = c(nanotime('2011-12-05 08:30:00.000',format ="%Y-%m-%d %H:%M:%E9S",  tz ="GMT"),
    +                                      nanotime('2011-12-05 08:30:00.100',format ="%Y-%m-%d %H:%M:%E9S",  tz ="GMT"),
    +                                      nanotime('2011-12-05 08:30:00.825',format ="%Y-%m-%d %H:%M:%E9S",  tz ="GMT")))
    R> 
    R> DT[, fmt := format(mt)]
    R> DT[]
                                        mt                                 fmt
    1: 2011-12-05T08:30:00.000000000+00:00 2011-12-05T08:30:00.000000000+00:00
    2: 2011-12-05T08:30:00.100000000+00:00 2011-12-05T08:30:00.100000000+00:00
    3: 2011-12-05T08:30:00.825000000+00:00 2011-12-05T08:30:00.825000000+00:00
    R>