Kuo-Hsien Chang
Kuo-Hsien Chang

Reputation: 935

R as.POSIXct timezone issue

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.

Upvotes: 0

Views: 1134

Answers (1)

RHA
RHA

Reputation: 3862

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.

Upvotes: 6

Related Questions