How to prevent write.csv from changing POSIXct, dates and times class back to character/factors?

Catarina Aires picture Catarina Aires · Apr 25, 2014 · Viewed 7.3k times · Source

I have a .csv file with one field each for datetime, date and time. Originally they are all character fields and I have converted them accordingly. At the end of my code, if I do:

str(data)

I will get

datetime: POSIXct
date: Date
time: Class 'times'  atomic [1:2820392] (....) attr(*, "format")= chr "h:m:s"

Now, I am very happy with this and I want to create a .csv file, so this is what I have:

write.csv(data, file = "data.csv", row.names = FALSE)

I have also tried

write.table(data, "data.csv", sep = ",", row.names = FALSE)

And I get the same result with both, which is all my convertion gets lost when writing the new .csv: everything is back to being a character.

I suspect I am missing some argument in the write function, but I have been searching all afternoon and I can't find out what. Can some please help?

Answer

David Sterratt picture David Sterratt · Apr 23, 2015

If you want to preserve all of the time information so it can be read in again, this recipe should work:

dat <- data.frame(time=as.POSIXlt("2013-04-25 09:00 BST"), quantity=1)
dat2 <- dat
dat2$time <- format(dat2$time, usetz=TRUE)
write.csv(dat2, "time.csv", row.names=FALSE)

It gives the following CSV file:

"time","quantity"
"2013-04-25 09:00:00 BST",1

in which the timezone information is presented explicitly; if you apply write.csv to the original dat, the formatting is lost.