Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read a csv with a timestamp field?

Tags:

r

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?

like image 205
Chris Snow Avatar asked Dec 02 '14 19:12

Chris Snow


People also ask

What does parse_dates in Read_csv do?

Reading Timestamps From CSV Files We can use the parse_dates parameter to convince pandas to turn things into real datetime types. parse_dates takes a list of columns (since you could want to parse multiple columns into datetimes ).

What does parse_dates do?

Converts text to a date.


1 Answers

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

like image 93
Achim Zeileis Avatar answered Sep 24 '22 12:09

Achim Zeileis