R as.POSIXct() dropping hours minutes and seconds

懵懂的女人 提交于 2019-12-04 09:17:31

You can try the code below.
It will:

  • read datetime type as character instead of factor
  • update by reference

library(data.table)
data <- fread("C:/RData/house2_electricity_main.csv")
data[, V1 := as.POSIXct(V1)]

There was a question recently about usage of fasttime::fastPOSIXct instead of as.POSIXct which can additionally speed up.

As for the title question, having POSIXct you can round it quite freely, e.g. functions year,month,mday...

data[, .SD, by = .(year(V1),month(V1),mday(V1))]

Maybe the reason for your problem is that you have dates without time somewhere in your data set. Try the following example:

  library(lubridate)
  dates <- as.character(now() + minutes(1:5))
  dates <- c(dates,"2015-05-10")
  as.POSIXct(dates[1:5])
  as.POSIXct(dates)

It first creates a vector dates containing 6 dates with times and converts them to character. Then I add another date (as a character) that does not contain a time. When you run the two conversions to POSIXct, you'll notice that the times are gone in the result, as soon as you include the date without time.

So there seems to be no date without time in the first few rows of your data, but later there maybe will be. There are most likely many solutions for this problem and I'll just propose one that came to my mind.

The first step is to change your read command, such that the dates are stored as characters instead of factors:

data <- read.csv("C:/RData/house2_electricity_Main.csv",header=FALSE,stringsAsFactors=FALSE)

Then you can try to add the time to all the dates that have none and convert to POSIXct only afterwards:

data$V1 <- ifelse(nchar(data$V1) > 11,data$V1, paste0(data$V1,"00:00:00"))
data$V1 <- as.POSIXct(data$V1)

This worked for my little example above. It is not the most elegant solution and maybe someone has a better idea.

Andrew

I had a similar problem with as.POSIXlt(X) dropping the hour:minute:second information, with X being a vector of POSIXct objects, that happened to have tzone="UTC".

However, as.POSIXlt(X, tz="UTC") kept the hour:minute:second information.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!