[R] Converting time from HH:MM:SS to only HH:MM

Bill.Venables at csiro.au Bill.Venables at csiro.au
Wed Mar 18 00:20:40 CET 2009


Dear Neotropical Bat Risk Assessments,

Rounding is the problem.  If you just want to lop off the seconds that is easy.  For example:

> d <- strptime(date(), "%a %b %d %H:%M:%S %Y")
> d
[1] "2009-03-18 08:52:41"
> format(d, "%Y-%m-%d %H:%M")
[1] "2009-03-18 08:52"

Here is a one way to do the rounding:

> e <- structure(round(as.numeric(as.POSIXct(d))/60)*60, class = "POSIXct")
> e
[1] "2009-03-18 08:53:00 EST"
> format(e, "%Y-%m-%d %H:%M")
[1] "2009-03-18 08:53"
> 

Another way to do it would be to work with POSIXlt object directly:

> e <- d
> e$min <- ifelse(d$sec > 30, d$min+1, d$min)
> e$sec <- 0
> e
[1] "2009-03-18 08:53:00"
> format(e, "%Y-%m-%d %H:%M")
[1] "2009-03-18 08:53"
> 

You can make the rounding definition more elaborate if you wish.
 
Everything here is vectorized, so 'd' can just as well be a vector of times as a single time as in this example.

(I must say I feel very uneasy about giving advice on how to use R as a pre-processor for something that is to be done in Excel, but we are a broad church here!)

Bill Venables
http://www.cmis.csiro.au/bill.venables/ 


-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Neotropical bat risk assessments
Sent: Wednesday, 18 March 2009 8:34 AM
To: r-help at r-project.org
Subject: [R] Converting time from HH:MM:SS to only HH:MM

Hi all,

I need to compare between times and put all similar times in specific 
1 minute bins.
Unfortunately the original data include seconds as well.

My data is in HH:MM:SS format but I need it rounded to only HH:MM and 
trying in Excel to display "unique" records only does not work since 
the seconds are not unique.

Is there an easy way using perhaps CHRON to change all from the 
HH:MM:SS data to a new HH:MM only data set and save as a TXT or CSV file?

Tnx

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list