[Rd] fractional seconds in POSIXct

Simon Urbanek simon.urbanek at r-project.org
Wed May 30 20:51:48 CEST 2012


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

> 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?

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:

> t <- as.POSIXct(strptime(datetime, format="%d/%m/%Y %H:%M:%OS"), tz="GMT")
> format(t, "%d/%m/%Y %H:%M:%OS5")
[1] "20/09/2011 13:00:59.00000" "20/09/2011 13:00:59.01999" "20/09/2011 13:00:59.03999"
> format(t, "%d/%m/%Y %H:%M:%OS2")
[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:

> as.numeric(t) %% 60
[1] 59.00 59.02 59.04

or if you add a half fraction (effectively forcing rounding):

> format(t + 0.005, "%d/%m/%Y %H:%M:%OS2")
[1] "20/09/2011 13:00:59.00" "20/09/2011 13:00:59.02" "20/09/2011 13:00:59.04"

Cheers,
Simon



>  Thanks.
> 
> Cheers,
> 
> -- 
> Seb
> 
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
> 
> 



More information about the R-devel mailing list