How to extract correct date from POSIXct element? [duplicate]

最后都变了- 提交于 2019-12-02 04:22:30

问题


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

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