Convert local date to UTC in R

How can I convert a 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 that doesn't seem to be valid.

+3


source to share


1 answer


If you want to convert datetime from the current timezone to UTC, you need to import in your timezone and then just change the display timezone to "UTC". for example: 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 change 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 does not affect the underlying numeric data (seconds since 1970-01-01), it only changes what is displayed.

+12


source







All Articles