Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert local dateTime to UTC in R

How can I convert local DateTime in the following format "12/31/2014 6:42:52 PM" to UTC in R? I tried this

as.POSIXct(as.Date("12/31/2014 6:42:52 PM", format="%m/%d/%Y %H:%M:%S"),tz="UTC")

but it doesn't seem to be valid.

like image 545
Sam Avatar asked Apr 16 '15 23:04

Sam


1 Answers

If you want to shift a datetime from your current timezone to UTC, you need to import in your local timezone, then just shift the display timezone to "UTC". e.g.: in Australian EST I am UTC+10.

out <- as.POSIXct("12/31/2014 6:42:52 PM", format="%m/%d/%Y %H:%M:%S")
out
#"2014-12-31 06:42:52 EST"
#(Australian Eastern Standard Time)
as.numeric(out)
#[1] 1419972172

Now shift the timezone for display purposes:

attr(out, "tzone") <- "UTC" 
out
#[1] "2014-12-30 20:42:52 UTC" 
# display goes 10 hours backwards as I'm UTC+10
as.numeric(out)
#[1] 1419972172

Note that this doesn't affect the underlying numeric data (seconds since 1970-01-01), it only changes what is displayed.

like image 188
thelatemail Avatar answered Oct 25 '22 04:10

thelatemail