How to change the default time zone in R?

房东的猫 提交于 2019-11-26 19:55:01

Another way to do it, without changing the whole computer time is using the setenv command like this : Sys.setenv(TZ='GMT')

See this good article on changing time zone in R:

http://blog.revolutionanalytics.com/2009/06/converting-time-zones.html

Shortly (in case the link will be unavailable in the future):

# your time string
pb.txt <- "2009-06-03 19:30"
# convert it to R object for London time zone
pb.date <- as.POSIXct(pb.txt, tz="Europe/London")
# convert it to PDT time zone
format(pb.date, tz="America/Los_Angeles",usetz=TRUE)
[1] "2009-06-03 11:30:00 PDT"

# can be also done for many date at once
d <- c("2009-03-07 12:00", "2009-03-08 12:00", "2009-03-28 12:00", "2009-03-29 12:00", "2009-10-24 12:00", "2009-10-25 12:00", "2009-10-31 12:00", "2009-11-01 12:00")
t1 <- as.POSIXct(d,"America/Los_Angeles")
cbind(US=format(t1),UK=format(t1,tz="Europe/London"))

     US                    UK                   
[1,] "2009-03-07 12:00:00" "2009-03-07 20:00:00"
[2,] "2009-03-08 12:00:00" "2009-03-08 19:00:00"
[3,] "2009-03-28 12:00:00" "2009-03-28 19:00:00"
[4,] "2009-03-29 12:00:00" "2009-03-29 20:00:00"
[5,] "2009-10-24 12:00:00" "2009-10-24 20:00:00"
[6,] "2009-10-25 12:00:00" "2009-10-25 19:00:00"
[7,] "2009-10-31 12:00:00" "2009-10-31 19:00:00"
[8,] "2009-11-01 12:00:00" "2009-11-01 20:00:00"

What operating system?

In general, see help(Startup) as you can set values via .Renviron and its site-wide variant.

But you should probably set this for your machine as a whole, which under Linux may alter the file /etc/timezone, and on Windows you'd set a system-wide environment variable TZ.

Lastly, if your formatted display of dates and time shows CET/CEST, this may already be set as a system default and your question really is how to set your UTC times correctly in your R objects.

I found @Dirk's answer very useful for Ubuntu, so I thought I would expand on it.

From help(Startup) we see that environment variables are set by the Renviron.site file:

Unless --no-environ was given on the command line, R searches for site and user files to process for setting environment variables. The name of the site file is the one pointed to by the environment variable R_ENVIRON; if this is unset, ‘R_HOME/etc/Renviron.site’ is used

We can find the path to R_HOME by using the function R.home(), which in my case returns:

> R.home()
[1] "/usr/lib/R"

Therefore, the Renviron.site file is found (for me) in /usr/lib/R/etc/.

Simply open this file, and insert the line:

TZ="UTC"

or similar.

-Changing the whole OS timezone is a sledgehammer for what is basically just intended to change programming algorithms. -Changing the start-up file does not lend itself to sharing code via git.

Is there another way to do it at script run time for the R session?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!