0

I'm confused by the as.POSIXct in R.

I use the following code to convert values in columns to one column with Date and Time.

  fname$DateTime <- as.POSIXct(paste(fname$yy, fname$mm, fname$dd, fname$HH, fname$MM), format = "%y %m %d %H %M")

Then, I set a time limit for plotting.

  lims <- as.POSIXct(strptime(c("2015-10-23 4:00","2015-10-23 16:00"), format = "%Y-%m-%d %H:%M")) 
  Temp <- ggplot(DF, aes(x=DateTime, y=Temp)) + geom_line(aes(x=DateTime, y=Temp),colour="blue", alpha = 0.8) + scale_x_datetime(limits =lims, breaks=date_breaks("1 hour"), labels=date_format("%m/%d %H:%M")) + facet_wrap( ~ ID, ncol=4)
  Temp + geom_vline(xintercept=as.numeric(as.POSIXct("2015-10-23 10:30")), linetype=4, colour="purple") 

enter image description here

The time series starts at 10/23 08:00 instead of 10/23 4:00; ends at 10/23 20:00 instead of 10/23 16:00. The vertical line shows at 10/23 14:30 instead of 10/23 10:30. It is a 4-hour time shift!

What is that happened? How can I just show the right time series as the DateTime showed in the data frame? Please help me!

Thanks.

Kuo-Hsien Chang
  • 925
  • 17
  • 40

1 Answers1

6

If you use as.POSIXct without specifying the timezone, it assumes the times you enter are utc and it also assumes you want them converted into the local timezone. Why it makes these often false assumptions is beyond me...
Try as.POSIXct(..., tz=<enter your timezone>)

If you do not know your timezone, Sys.timezone(location = TRUE) will tell you what your timezone is.

RHA
  • 3,677
  • 4
  • 25
  • 48
  • Great! It matches with with the GMT timezone. HOWEVER, geom_vline(xintercept=as.numeric(as.POSIXct("2015-10-23 10:30")) did not show where it should be. It is plotted at 2015-10-23 14:30. It should be at 2015-10-23 10:30. Any ideas? – Kuo-Hsien Chang Mar 07 '16 at 18:23
  • @kuo-hsienchang same issue. Add a timezone to the `as.POSIXct` function. – RHA Mar 07 '16 at 18:48
  • 1
    I added "tz="UTC" to both of them. It did not work as I expected. – Kuo-Hsien Chang Mar 07 '16 at 19:36
  • 1
    @Kuo-hsienchang No you should add your local timezone. If you you don't know what it is, try `Sys.timezone(location = TRUE)` – RHA Mar 07 '16 at 19:43