Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

with_timezone() ? #92

Closed
gaborcsardi opened this issue May 8, 2019 · 7 comments · Fixed by #93
Closed

with_timezone() ? #92

gaborcsardi opened this issue May 8, 2019 · 7 comments · Fixed by #93

Comments

@gaborcsardi
Copy link
Member

I realize this is somewhat niche, but it can be useful for testing package that deal with timestamps.

The implementation is mostly straightforward, I can submit a PR, I need to write this for the parsedate package, anyway.

@gaborcsardi
Copy link
Member Author

gaborcsardi commented May 8, 2019

It seems that this would do it, although I still need to test it on older R versions, I am not sure when the cache was introduced:

with_timezone <- function(tzone, expr) {
  ## Need to remove the cache first, and also on exit
  clear <- function() assign(".sys.timezone", NA, envir = baseenv())
  clear()
  on.exit(clear(), add = TRUE)
  with_envvar(c(TZ = tzone), expr)
}
Sys.timezone()
#> [1] "Europe/London"

with_timezone("CET", Sys.timezone())
#> [1] "CET"

@gaborcsardi
Copy link
Member Author

gaborcsardi commented May 8, 2019

We could probably also just restore the cache on exit, instead of setting it to NA. Just in case:

with_timezone <- function(tzone, expr) {
  old <- get0(".sys.timezone", baseenv(), mode = "character",
              inherits = FALSE, ifnotfound = NA_character_)
  on.exit(assign(".sys.timezone", old, envir = baseenv()), add = TRUE)
  assign(".sys.timezone", NA, envir = baseenv())
  withr::with_envvar(c(TZ = tzone), expr)
}

@gaborcsardi
Copy link
Member Author

gaborcsardi commented May 8, 2019

Actually, there is something more to it, because this does not work:

with_timezone("US/Pacific", Sys.time())
#> [1] "2019-05-08 10:44:45 BST"

EDIT: no, it is good, just need to print inside:

with_timezone("US/Pacific", print(Sys.time()))
#> [1] "2019-05-08 02:45:43 PDT"

@jimhester
Copy link
Member

I think it is definitely worthwhile to have in withr, particularly because it has some fiddly bits with the cache. So a PR would be great!

@gaborcsardi
Copy link
Member Author

OK, I have an implementation in parsedate, so I'll submit a PR soon.

@gaborcsardi
Copy link
Member Author

Do you want to call it with_tz() or with_timezone() or with_time_zone() or sg else?

@jimhester
Copy link
Member

I guess with_timezone() to match Sys.timezone().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants