Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting to Local Time in R - Vector of Timezones

I have a set of data from across the US that I am trying to convert into local time for each "subject". I have UTC timestamps on each event and have converted those into POSIXct format, but every time I try to include a vector of tz = DS$Factor or tz = as.character(DS$Factor) in any of the POSIXct/POSIXlt functions (including format() and strftime()) I get an error that says:

Error in as.POSIXlt.POSIXct(x, tz = tz) : invalid 'tz' value

If I just enter tz = 'US/Eastern' it works fine, but of course not all of my values are from that time zone.

How do I get the time stamps into local time for each "subject"?

The DS$Factor has 5 values: US/Arizona US/Central US/Eastern US/Mountain US/Pacific

Thanks, Shorthand

like image 429
Shorthand Avatar asked Oct 19 '22 04:10

Shorthand


1 Answers

Bringing in dplyr and lubridate, I wound up doing something like:

require(lubridate)
require(dplyr)

df = data.frame(timestring = c("2015-12-12 13:34:56", "2015-12-14 16:23:32"),
                localzone = c("America/Los_Angeles", "America/New_York"), stringsAsFactors = F)

df$moment = as.POSIXct(df$timestring, format="%Y-%m-%d %H:%M:%S", tz="UTC")

df = df %>% rowwise() %>% mutate(localtime = force_tz(moment, localzone))

df
like image 179
schnee Avatar answered Oct 27 '22 08:10

schnee