Question

I am having an issue in converting a POSIXct vector to Date format using as.Date which seems to translate 2013-09-30 to 2013-10-01, see below:

  > test$Submit
  [1] "2013-09-30 22:40:24 EST" "2013-09-30 21:07:40 EST" "2013-09-30 19:17:23 EST"
  [4] "2013-09-30 19:28:30 EST" "2013-09-30 23:55:25 EST" "2013-09-30 19:19:26 EST"
  [7] "2013-09-30 19:31:57 EST" "2013-09-30 19:38:55 EST" "2013-09-30 19:52:48 EST"
  [10] "2013-09-30 19:57:34 EST" "2013-09-30 20:19:12 EST" "2013-09-30 23:59:24 EST"
  [13] "2013-09-30 19:38:23 EST" "2013-09-30 20:27:34 EST" "2013-09-30 22:35:00 EST"
  [16] "2013-09-30 22:37:48 EST" "2013-09-30 22:47:50 EST" "2013-09-30 23:06:07 EST"

   > str(test$Submit)
   POSIXct[1:18], format: "2013-09-30 22:40:24" "2013-09-30 21:07:40" "2013-09-30 19:17:23" ...

   > as.Date(test$Submit)
   [1] "2013-10-01" "2013-10-01" "2013-10-01" "2013-10-01" "2013-10-01" "2013-10-01"
   [7] "2013-10-01" "2013-10-01" "2013-10-01" "2013-10-01" "2013-10-01" "2013-10-01"
   [13] "2013-10-01" "2013-10-01" "2013-10-01" "2013-10-01" "2013-10-01" "2013-10-01"

Also, my Sys.time() shows that I am on EST. Any ideas on what maybe happening?

Was it helpful?

Solution

Try setting timezone in as.Date:

> dt <- as.POSIXct("2013-09-30 22:40:24 EST")
> dt
[1] "2013-09-30 22:40:24 EDT"
> as.Date(dt)
[1] "2013-10-01"
> as.Date(dt, tz="EST")
[1] "2013-09-30"

EDIT: I was about to post what Roland commented on, and you can see that by looking at the attributes:

> attributes(dt)
$class
[1] "POSIXct" "POSIXt" 

$tzone
[1] ""

So even though you think you're setting stuff to EST, you're not. The default is actually to local time (tz="") for as.POSIXct:

A timezone specification to be used for the conversion, if one is required. System-specific (see time zones), but "" is the current timezone, and "GMT" is UTC (Universal Time, Coordinated).

But then for as.Date.POSIXct, the default is UTC!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top