Skip to content

fractional seconds in POSIXct

2 messages · Sébastien Bihorel, Simon Urbanek

#
Hi,

Using the following simple character vector representing a time series
with fractional seconds:

datetime <- c("20/09/2011 13:00:59.00", "20/09/2011 13:00:59.02",
              "20/09/2011 13:00:59.04")

Conversion to POSIXct runs into problems; the second element is not
interpreted correctly:

---<--------------------cut here---------------start------------------->---
R> as.POSIXct(strptime(datetime, format="%d/%m/%Y %H:%M:%OS"), tz="GMT")
[1] "2011-09-20 13:00:59.00 GMT" "2011-09-20 13:00:59.01 GMT" "2011-09-20 13:00:59.03 GMT"
R> sessionInfo()
R version 2.15.0 (2012-03-30)
Platform: x86_64-pc-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_CA.UTF-8       LC_NUMERIC=C               LC_TIME=en_CA.UTF-8        LC_COLLATE=en_CA.UTF-8     LC_MONETARY=en_CA.UTF-8   
 [6] LC_MESSAGES=en_CA.UTF-8    LC_PAPER=C                 LC_NAME=C                  LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_CA.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats4    stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] diveMove_1.3.4      caTools_1.12        bitops_1.0-4.1      slmisc_0.9.2        latticeExtra_0.6-19 RColorBrewer_1.0-5  lattice_0.20-6     

loaded via a namespace (and not attached):
[1] compiler_2.15.0 grid_2.15.0     tools_2.15.0   
---<--------------------cut here---------------end--------------------->---

Is this expected?  Thanks.

Cheers,
#
On May 30, 2012, at 2:15 PM, Sebastian P. Luque wrote:

            
Yes, your dates are not exactly representable in FP and you are implicitly using %OS2 for display, so your values get truncated - to see it more clearly:
[1] "20/09/2011 13:00:59.00000" "20/09/2011 13:00:59.01999" "20/09/2011 13:00:59.03999"
[1] "20/09/2011 13:00:59.00" "20/09/2011 13:00:59.01" "20/09/2011 13:00:59.03"

If you round them you'll get what you expected:
[1] 59.00 59.02 59.04

or if you add a half fraction (effectively forcing rounding):
[1] "20/09/2011 13:00:59.00" "20/09/2011 13:00:59.02" "20/09/2011 13:00:59.04"

Cheers,
Simon