[R] Converting the time in a numeric value
Prof Brian Ripley
ripley at stats.ox.ac.uk
Sun Jul 10 09:15:00 CEST 2011
On Sun, 10 Jul 2011, Amy Ruiz Goyco wrote:
> Hello:
> I am new using R. I have a file that contain in the same columns
> date and time like for example 2011/10/03 12:34:45.123423 p.m., but
> when I read the file and display the vector, I see of this way
> "2011-10-03 12:34:45.123423". I need to convert the time in a
> numeric and the date if is possible, but I don't need this to
> compute. Thus, I used this tiempo=substr(time,12,26) to selected
> the data that I need, but I don't know how I can change this to a
> numeric values.
You need to clarify what you mean by 'date' and 'numeric' here. At a
guess, 'numeric' might mean 'number of seconds past midnight'. We
can't even do that, since we don't know the timezone (and it differs
on DST transition days). So you need to read a well-informed article
on date-times (not the un-refereed one in R-News 4/1) to gain more
understanding.
Also, your AM/PM indicator is very non-standard.
But here are some pieces for you to work with
dt <- "2011/10/03 12:34:45.123423 p.m."
t0 <- substr(dt, 12, 26)
PM <- substr(dt, 28, 31)
date <- strptime(dt, "%Y/%m/%d")
t1 <- unclass(as.POSIXct(paste("1970-01-01", t0)))
time <- ifelse(PM == "p.m.", t1+12*3600, t1)
> date
[1] "2011-10-03"
> print(time, digits=12)
[1] 84885.123423
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
More information about the R-help
mailing list