6

I'm trying to import a csv file that has a field Ts containing ISO8601 time stamp values (E.g. 2014-12-01T18:54:22.973+0000).

I have seen that you can specify the class of columns:

kd <- read.csv( "my.csv", colClasses=c( "Ts"="?"  ))

However, I can't find how to declare a timestamp field.

Question: How can I specify that this field is a time stamp?

Chris Snow
  • 23,813
  • 35
  • 144
  • 309
  • You need to use `setAs` to make a function that can handle that colClass. e.g.: http://stackoverflow.com/a/3611619/967840, http://stackoverflow.com/a/10823641/967840 – GSee Dec 02 '14 at 20:45

2 Answers2

4

If you want to read the .csv file directly into a time series object, you can use the function read.zoo() from the zoo package. This internally calls read.table() (rather than read.csv) and then converts the specified time index column(s). See ?read.zoo and vignette("zoo-read", package = "zoo").

An example with time stamps like yours is:

csv <-
"x,y,timestamp
0,1,2014-12-01T18:54:22.973+0000
1,2,2014-12-01T19:43:11.862+0000"
read.zoo(text = csv, sep = ",", header = TRUE, index = "timestamp",
  format = "%Y-%m-%dT%H:%M:%OS%z", tz = "GMT")

And this yields a zoo series with POSIXct time stamps:

                    x y
2014-12-01 18:54:22 0 1
2014-12-01 19:43:11 1 2

(Of course, the text = csv would have to be replaced by something like file = "my.csv" if you are reading a .csv file from the disk rather than a text string from within R.)

Achim Zeileis
  • 15,710
  • 1
  • 39
  • 49
2

Don't know of a way to do it directly on the read, but as a workaround (until someone more knowledgeable answers) you can do the conversion afterwords:

kd <- read.csv("my.csv")
%  Assume that the timestamp column in the csv file has the header 'timestamp'

kd$newtimestamp <- strptime(kd$timestamp,format="%FT%H:%M:%OS%z")

%  By default this will convert all times to your timezone 
%  but you can control the conversion through the tx argument e.g. tx='GMT' 
Jim Quirk
  • 606
  • 5
  • 18