John Thomas
John Thomas

Reputation: 1105

Converting timeszone dates in R

So I have a dataframe as follows:

dates <- structure(list(Date = c("2018-01-03", "2018-01-03", "2018-01-04", 
"2018-01-08", "2018-01-09")), row.names = c(NA, 5L), class = "data.frame")

And I can "successfully" generate sunrise/sunset times for each date with the following:

library(httr)
library(jsonlite)

dates %>% 
  rowwise() %>% 
  mutate(sunrise = as.character(fromJSON(rawToChar(GET(paste0("https://api.sunrise-sunset.org/json?lat=40.730610&lng=-73.935242&date=", Date))$content))$results[1]),
         sunset = as.character(fromJSON(rawToChar(GET(paste0("https://api.sunrise-sunset.org/json?lat=40.730610&lng=-73.935242&date=", Date))$content))$results[2])
  )

And thus:

    
Date            sunrise     sunset
2018-01-03  12:19:53 PM 9:41:13 PM
2018-01-03  12:19:53 PM 9:41:13 PM
2018-01-04  12:19:52 PM 9:42:08 PM
2018-01-08  12:19:27 PM 9:46:00 PM
2018-01-09  12:19:15 PM 9:47:01 PM

The problem here however is the dates are in UTC (I believe). The location I have here is New York City so these times above are 4 hours ahead. I wrote the following to fix the issue but I think I am over complicating things to move these times 4 hours back.

library(data.table)
dates %>% 
  rowwise() %>% 
  mutate(sunrise = as.character(as.ITime(as.character(fromJSON(rawToChar(GET(paste0("https://api.sunrise-sunset.org/json?lat=40.730610&lng=-73.935242&date=", Date))$content))$results[1])
           )-18000),
         sunset = as.character(as.ITime(as.character(fromJSON(rawToChar(GET(paste0("https://api.sunrise-sunset.org/json?lat=40.730610&lng=-73.935242&date=", Date))$content))$results[2])
         )-18000)
         )

But now I have lost AM/PM.

Date         sunrise    sunset
2018-01-03  07:19:53  04:41:13
2018-01-03  07:19:53  04:41:13
2018-01-04  07:19:52  04:42:08
2018-01-08  07:19:27  04:46:00
2018-01-09  07:19:15  04:47:01

In short, how could I make this work so I can get the date for what the API spits out in the NYC time.

Upvotes: 1

Views: 36

Answers (1)

akrun
akrun

Reputation: 886938

An option is to convert to POSIXct and then format after doing the transformation

dates %>% 
   rowwise() %>% 
   mutate(sunrise = as.character(fromJSON(rawToChar(GET(paste0("https://api.sunrise-sunset.org/json?lat=40.730610&lng=-73.935242&date=", Date))$content))$results[1]),
          sunset = as.character(fromJSON(rawToChar(GET(paste0("https://api.sunrise-sunset.org/json?lat=40.730610&lng=-73.935242&date=", Date))$content))$results[2])
   ) %>%
   mutate(sunrise = toupper(format(as.POSIXct(sunrise, format = "%I:%M:%S %p") - 18000, "%I:%M:%S %p")))
# A tibble: 5 x 3
# Rowwise: 
#  Date       sunrise     sunset    
#  <chr>      <chr>       <chr>     
#1 2018-01-03 07:19:53 AM 9:41:13 PM
#2 2018-01-03 07:19:53 AM 9:41:13 PM
#3 2018-01-04 07:19:52 AM 9:42:08 PM
#4 2018-01-08 07:19:27 AM 9:46:00 PM
#5 2018-01-09 07:19:15 AM 9:47:01 PM

Upvotes: 1

Related Questions