15

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.

Mamoun Benghezal
  • 5,264
  • 7
  • 28
  • 33
Sam
  • 155
  • 1
  • 1
  • 5
  • 2
    did you try `strptime("12/31/2014 6:42:52 PM", format="%m/%d/%Y %H:%M:%S",tz="UTC")` ? – Mamoun Benghezal Apr 16 '15 at 23:36
  • What is your current timezone in R console, type `Sys.timezone()` – ccapizzano Apr 17 '15 at 00:04
  • `as.POSIXct("12/31/2014 6:42:52 PM", format="%m/%d/%Y %H:%M:%S",tz="UTC")` - drop the `as.Date()` part in the middle. It's not needed and it just means you cut the time component, stuffing up the conversion. @MamounBenghezal 's answer also returns a `POSIXlt` instead of a `POSIXct` date/time. Use `as.POSIXct` in preference as it is generally more adaptable. – thelatemail Apr 17 '15 at 00:10
  • Please note that I need to convert "12/31/2014 6:42:52 PM" which is local DateTime to UTC. – Sam Apr 17 '15 at 00:23
  • As presented, your date and time are at the same time local time and UTC. –  Apr 17 '15 at 01:11

1 Answers1

29

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.

thelatemail
  • 91,185
  • 12
  • 128
  • 188