2

I am just learning R and have come up against this.

I have the below time series observations,

10/08/2015 02:31:04.450
  • I want to split the date and the time to separate columns.
  • Do i need need to round the Milliseconds in time? if so how.

I have been looking at, data table, lubridate to try and figure it out. I looked at XTS but that seems to be more orientated to aggregation of dates.

Are they any existing packages in R that allows for this splitting? and what sort of argument would I use.

Any help would be much appreciated.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Hilly
  • 21
  • 1

3 Answers3

5

Using data.table it is very straight forward:

require(data.table)
x <- "10/08/2015 02:31:04.450"
IDateTime(strptime(x, "%d/%m/%Y %H:%M:%OS"))

gives you the following data.table

        idate    itime
1: 2015-08-10 02:31:04
Rentrop
  • 20,979
  • 10
  • 72
  • 100
3
x <- "10/08/2015 02:31:04.450"
temp <- strptime(x, "%d/%m/%Y %H:%M:%OS")

format(temp,"%H:%M:%S")
#[1] "02:31:04"

as.Date(temp)
#[1] "2015-08-10"

If you do not need the time part in character form you can add few steps

x <- "10/08/2015 02:31:04.450"
temp <- strptime(x, "%d/%m/%Y %H:%M:%OS")

library(chron)
chron(times = format(temp,"%H:%M:%S"))
#[1] 02:31:04

class(chron(times = format(temp,"%H:%M:%S")))
#[1] "times"

as.Date(temp)
# [1] "2015-08-10"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0
string_timeStamp = "10/08/2015 02:31:04.450"
parsed_timeStamp = strptime(string_timeStamp, "%d/%m/%Y %H:%M:%OS")

date_time_dataFrame = data.frame(date = cut(parsed_timeStamp, breaks = "days"), 
                             time = format(parsed_timeStamp, "%H:%M:%OS" ))

For more formatting options, check ?strptime

  • many thanks Deena, I did play around with strptime, but I clearly didn't get the right argument. – Hilly Sep 29 '15 at 09:24