change timezone for some POSIXct entries in a data frame in R

941 views Asked by At

I am having difficulty changing time zones for POSIXct object. Following the suggestion in: Change timezone in a POSIXct object

I tried

> test
    timestamp            dttm_utc   value estimated anomaly SITE_ID
954157 1328043600 2012-02-01 00:00:00 16.4803         0      NA      31
954158 1328043900 2012-02-01 00:05:00 16.4364         0      NA      31
> attributes(test[2,2])$tzone
     TIME_ZONE 
"America/New_York" 
> attributes(test[2,2])$tzone <- "America/Los_Angeles"
> attributes(test[2,2])$tzone
     TIME_ZONE 
"America/New_York" 

Why does this not work? How can I solve this problem?

1

There are 1 answers

0
MrFlick On BEST ANSWER

The problem is that tzone is a property of the entire vector. Each element cannot have their own timezone. You can change the timezone for the entire vector. Consider this example

x<-as.POSIXct(c("2012-02-01 00:00:00","2012-02-01 00:05:00"), tz="America/New_York")
attributes(x[1])$tzone
# [1] "America/New_York"

# does not change
attributes(x[1])$tzone<-"America/Los_Angeles"
attributes(x[1])$tzone
# [1] "America/New_York"

#changes
attributes(x)$tzone<-"America/Los_Angeles"
attributes(x[1])$tzone
# [1] "America/Los_Angeles"

If you have dates from different time zones, you can specify the time zone with a UTC offset and then they will all be converted to a common timezone

x<-as.POSIXct(c("2012-02-01 00:00:00-0800","2012-02-01 00:05:00-0500"), 
    format="%Y-%m-%d %H:%M:%S%z", tz="America/Los_Angeles")
# [1] "2012-02-01 00:00:00 PST" "2012-01-31 21:05:00 PST"