6

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?

Azametzin
  • 5,223
  • 12
  • 28
  • 46
Aki
  • 409
  • 2
  • 6
  • 15
  • You probably have daylight saving issues. You''ll need to specify your timezone for both, for example `test$posixdate <- as.POSIXct(test$posixdate, tz = "GMT") ; as.Date(test$posixdate, tz = "GMT")` – David Arenburg Mar 23 '15 at 09:40
  • Thank you! I suppose "CET" does not automatically consider daylight-saving periods? – Aki Mar 23 '15 at 09:49
  • `as.Date` ignores it. Just do `test$posixdate <- as.POSIXct(test$posixdate, tz = "CET") ; as.Date(test$posixdate, tz = "CET")` – David Arenburg Mar 23 '15 at 09:51
  • Perfect! Thanks a lot. If you posted your solution as an answer I could accept it. – Aki Mar 23 '15 at 09:57
  • This is a duplicate and already has an answer in previous questions so no need to post another similar solution. Though, I admit this is a hard thing to understand by your own for a new R user thus I've upvoted your question. – David Arenburg Mar 23 '15 at 10:01
  • One last question: Does as.POSIXct() use local (system) time zone if not otherwise given (tz="") while as.Date() uses "GMT" if not given directly? – Aki Mar 23 '15 at 11:01
  • The default of `as.Date` is UTC. Read `?as.Date` – David Arenburg Mar 23 '15 at 11:05

2 Answers2

4

the problem is the timezone

try your timezone (probably not GMT)

test$date2 <- as.Date(test$posixdate, "GMT")

and read this post

Community
  • 1
  • 1
rmuc8
  • 2,869
  • 7
  • 27
  • 36
1

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"
Miha Trošt
  • 2,002
  • 22
  • 25