[R] Re : Seperate timestamp data into date and time

Dirk Eddelbuettel edd at debian.org
Tue Oct 18 06:15:12 CEST 2005


On 18 October 2005 at 16:32, ssim at lic.co.nz wrote:
| I am reading in text file data prepared in Access database by someone. One
| of the field contains timestamp data, how can I separate the timestamp data
| into two varaibles: date and time. Can I specify the field is in timestamp
| format when I first reading in ?
| 
| My reading in data are as below:
| 
| 449  LWT  22/10/2003 15:43:00  441  143
| 449  LWT  17/11/2003 15:25:00  421  169
| 449  LWT  14/11/2003 15:04:00  454  166
| 449  LWT   17/12/2003 5:55:00  428  199
| 449  LWT   7/12/2003 15:28:00  452  189
| 449  LWT  15/11/2003 15:20:00  457  167

You probably don't want to split it into date and time, but rather read it
into R's DateTimeClasses which encompass both:

Let's assign the time to a variable:
> datetimes <- c("22/10/2003 15:43:00", "17/11/2003 15:25:00", "14/11/2003 15:04:00", "17/12/2003 5:55:00", "7/12/2003 15:28:00", "15/11/2003 15:20:00")
> datetimes
[1] "22/10/2003 15:43:00" "17/11/2003 15:25:00" "14/11/2003 15:04:00"
[4] "17/12/2003 5:55:00"  "7/12/2003 15:28:00"  "15/11/2003 15:20:00"

and then read them using the strptime() function with a matching argument:

> parsed <- strptime(datetimes, "%d/%m/%Y %H:%M:%S")
> parsed
[1] "2003-10-22 15:43:00" "2003-11-17 15:25:00" "2003-11-14 15:04:00"
[4] "2003-12-17 05:55:00" "2003-12-07 15:28:00" "2003-11-15 15:20:00"

That gives time objects:

> class(parsed)
[1] "POSIXt"  "POSIXlt"

The time classes are very, very powerful. They may also appear to be
confusing, so make sure you really the available documentation, incl some R
News articles, the help pages etc pp

These time objects can be formatted any way you want them:

> format(parsed, "%d/%m/%y")
[1] "22/10/03" "17/11/03" "14/11/03" "17/12/03" "07/12/03" "15/11/03"
> format(parsed, "%H:%M")
[1] "15:43" "15:25" "15:04" "05:55" "15:28" "15:20"
 
Hope this helps, Dirk

-- 
Statistics: The (futile) attempt to offer certainty about uncertainty.
         -- Roger Koenker, 'Dictionary of Received Ideas of Statistics'




More information about the R-help mailing list