[R] Date/Time to date & time

Gabor Grothendieck ggrothendieck at gmail.com
Sun Sep 20 22:27:44 CEST 2009


Note that your explanation refers to strptime but the code uses
strftime which accounts for the error.

Try this:

> Lines <- "ENTRY DATE
+ 3/23/2009 6:30:00 AM
+ 3/23/2009 6:30:00 AM
+ 3/23/2009 6:39:00 AM
+ 3/23/2009 6:39:00 AM
+ 3/23/2009 6:48:00 AM
+ 3/23/2009 6:48:00 AM
+ 3/23/2009 7:00:00 AM"
>
> DF <- read.csv(textConnection(Lines))
> library(chron)
> ch <- as.chron(as.character(DF[[1]]), "%m/%d/%Y %I:%M:%S %p")
> dd <- dates(ch)
> data.frame(Date = dd, Time = times(ch - dd))
      Date     Time
1 03/23/09 06:30:00
2 03/23/09 06:30:00
3 03/23/09 06:39:00
4 03/23/09 06:39:00
5 03/23/09 06:48:00
6 03/23/09 06:48:00
7 03/23/09 07:00:00

Try using dput next time to facilitate copying of your data into
readers' sessions.

> dput(DF)
structure(list(ENTRY.DATE = structure(c(1L, 1L, 2L, 2L, 3L, 3L,
4L), .Label = c("3/23/2009 6:30:00 AM", "3/23/2009 6:39:00 AM",
"3/23/2009 6:48:00 AM", "3/23/2009 7:00:00 AM"), class = "factor")),
.Names = "ENTRY.DATE", class = "data.frame", row.names = c(NA,
-7L))

In the above we used dates and times classes from chron.  as.Date(x) will
convert an object to Date class if you want that instead.

See R News 4/1 for more on dates and times.

On Sun, Sep 20, 2009 at 4:11 PM, Mark Knecht <markknecht at gmail.com> wrote:
> Hi,
>    Can strptime (or some other function) help me turn the following
> column of a data.frame into two new columns, one as date and the other
> as time, preserving the AM/PM value?
>
> Thanks,
> Mark
>
>> B
>              ENTRY DATE
> 1  3/23/2009 6:30:00 AM
> 2  3/23/2009 6:30:00 AM
> 3  3/23/2009 6:39:00 AM
> 4  3/23/2009 6:39:00 AM
> 5  3/23/2009 6:48:00 AM
> 6  3/23/2009 6:48:00 AM
> 7  3/23/2009 7:00:00 AM
>
>> strftime(B, tz="", format="%m/%d/%Y %I:%M:%s %p")
> Error in as.POSIXlt.default(x, tz = tz) :
>  do not know how to convert 'x' to class "POSIXlt"
>>
>
>> strptime(B, format="%m/%d/%Y %I:%M:%s %p")
> [1] NA
>>
>
>> mode(B)
> [1] "list"
>> class(B)
> [1] "data.frame"
>>
>
> ______________________________________________
> 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