Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change from date time to numeric AND back to date time in R

Tags:

datetime

r

Seeing that others can't reproduce this Any speculation about system settings that might cause what I'm seeing would be appreciated. This is on a work PC configured by IT, but I will compare with my personal install this evening and then update the question.

Using base R, I'm trying to read in date and time, convert to numeric, and then convert back to date time. The problem I'm running into is a + 5 hour shift that gets introduced, I think due to timezone defaults.

From a previous question, an example of date time to numeric was provided: Change from date and hour format to numeric format

> x <- as.POSIXct("9/27/2011  3:33:00 PM", format="%m/%d/%Y  %H:%M:%S %p")
> x
[1] "2011-09-27 03:33:00 EDT"
> y <- as.numeric(x)
[1] 1317108780

*Typo in above code fixed

When I try to bring this back to date time, I get:

> z <- as.POSIXct(y, origin="1970-01-01")
> z
[1] "2011-09-27 08:33:00 EDT" 

I tried some variants, including specifying time zones explicitly, but am consistently getting this shift.

like image 301
joeln Avatar asked Dec 12 '14 14:12

joeln


1 Answers

I think it is just a problem of specifying time zones :

x <- as.POSIXct("9/27/2011  15:33:00", format="%m/%d/%Y  %H:%M:%S")
> as.POSIXct(as.numeric(x), origin="1970-01-01",tz="EST") # as.numeric(x)=1317130380
[1] "2011-09-27 08:33:00 EST"

but :

x <- as.POSIXct("9/27/2011  15:33:00", format="%m/%d/%Y  %H:%M:%S",tz="EST")
> as.POSIXct(as.numeric(x), origin="1970-01-01",tz="EST") # as.numeric(x)=1317155580
[1] "2011-09-27 15:33:00 EST"

remark : I simplified 03:33:00 PM in 15:33:00

like image 195
Cath Avatar answered Oct 12 '22 09:10

Cath