问题
How can I get the correct date from the first column in my code?
test <- data.frame(posixdate = c("2013-05-01 00:59:00", "2013-05-01 01:59:00", "2013-05-01 02:59:00", "2013-05-01 03:59:00"))
test$posixdate <- as.POSIXct(test$posixdate, format="%Y-%m-%d %H:%M:%S" )
test$date <- as.Date(test$posixdate)
The above code results in:
posixdate date
1 2013-05-01 00:59:00 2013-04-30
2 2013-05-01 01:59:00 2013-04-30
3 2013-05-01 02:59:00 2013-05-01
4 2013-05-01 03:59:00 2013-05-01
The first two dates are not correct. What did I do wrong? If as.Date() is not the right function, how could I get the date (without hours, minutes, seconds) alternatively?
Thanks in advance!
回答1:
the problem is the timezone
try your timezone (probably not GMT)
test$date2 <- as.Date(test$posixdate, "GMT")
and read this post
回答2:
Try with lubridate
package. It works for me.
library(lubridate)
as.Date(ymd_hms(test$posixdate))
[1] "2013-05-01" "2013-05-01" "2013-05-01" "2013-05-01"
来源:https://stackoverflow.com/questions/29206881/how-to-extract-correct-date-from-posixct-element