Chris Snow
Chris Snow

Reputation: 24596

how to read a csv with a timestamp field?

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?

Upvotes: 6

Views: 7932

Answers (2)

Achim Zeileis
Achim Zeileis

Reputation: 17183

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.)

Upvotes: 4

Jim Quirk
Jim Quirk

Reputation: 626

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' 

Upvotes: 2

Related Questions