Converting a date to POSIXct gives the result?

I am doing data retrieval from a database and running the results through rehsape2. For some reason, this causes POSIXct date and time stamps to be numeric. No problem, I think you can just bring them back, except that I am an hour.

Here is a minimal example

foo<-as.POSIXct("2011-04-04 14:18:58") as.numeric(foo) #gives 130192318 bar<-as.POSIXct(as.numeric(foo), tz=Sys.timezone(), origin=as.POSIXct( strptime("1970-01-01 00:00:00", "%Y-%m-%d %H:%M:%S", tz="UTC"))) as.numeric(bar) #gives 130192318 identical ! foo #Gives "2011-04-04 14:18:58 BST" bar #Gives "2011-04-04 13:18:58 UTC" 

Obviously, foo and bar are numerically identical, but R thinks that foo should display as BST and bar as UTC. How to get both values ​​as BST. This does not work either;

 as.POSIXct(bar, tz="BST") #still gives "2011-04-04 13:18:58 UTC" 
+7
source share
2 answers

This is what happens. bar is created using as.POSIXct.numeric , which is defined as:

 as.POSIXct.numeric function (x, tz = "", origin, ...) { if (missing(origin)) stop("'origin' must be supplied") as.POSIXct(origin, tz = tz, ...) + x } <environment: namespace:base> 

You are sending a source that is a POSIXct object. This means that a call to as.POSIXct in as.POSIXct.numeric sent to as.POSIXct.default , which is defined as:

 as.POSIXct.default function (x, tz = "", ...) { if (inherits(x, "POSIXct")) return(x) if (is.character(x) || is.factor(x)) return(as.POSIXct(as.POSIXlt(x, tz, ...), tz, ...)) if (is.logical(x) && all(is.na(x))) return(.POSIXct(as.numeric(x))) stop(gettextf("do not know how to convert '%s' to class \"POSIXct\"", deparse(substitute(x)))) } <environment: namespace:base> 

x is an object of the POSIXct class ( origin that you specified when you first called), so it just returns and the tz= argument tz= ignored.


UPDATE:
Here you can convert foo back to POSIXct with the appropriate time zone.

 (foo <- as.POSIXct("2011-04-04 14:18:58", tz="GB")) # [1] "2011-04-04 14:18:58 BST" .POSIXct(as.numeric(foo), tz="GB") # [1] "2011-04-04 14:18:58 BST" 
+13
source

Here is the part I used to get around this. By specifying the source as the current time minus the numeric version of the current time, the time zones do not seem to be screwed.

 foo<-as.POSIXct("2011-04-04 14:18:58") as.numeric(foo) #gives 130192318 bar<-as.POSIXct(as.numeric(foo), tz="GB", origin=Sys.time()-as.numeric(Sys.time())) as.numeric(bar) #gives 130192318 identical ! foo #Gives "2011-04-04 14:18:58 BST" [1] "2011-04-04 14:18:58 BST" bar #Gives "2011-04-04 14:18:58 BST" [1] "2011-04-04 14:18:58 BST 
+2
source

All Articles