R Programming: Correcting the Time-zone for a POSIX object

2017-06-08 13:09 PDT

The point of this entry is to document how to convert a date-time POSIXct object that has the correct date and time but the incorrect time-zone. I've found this issue arises when reading date-time information from an Excel or CSV file and they system automatically assumes the date-time is in UTC instead of the local time-zone.

To correct this issue, there are two basic steps:

  1. Convert the date-time POSIX object into a character string
  2. Convert the character string back into a POSIX object with the desired time-zone.

Pretty straight forward eh?

Here's an example:

 
# Let's generate a date for the local time but with UTC as the time-zone.
 date <- as.POSIXct("2017-06-08 13:09:00",tz="UTC")  
# RESULT
# date
# [1] "2017-06-08 13:09:00 UTC" # We want to correct the time-zone to PDT without changing the time # Convert the date into a string date_str <- format(date,format = "%y-%m-%d %H:%M:%S") # RESULT # date_str # [1] "17-06-08 13:09:00" # We can now convert the string back to a POSIXct object with the desired time-zone date_local <- as.POSIXct(date_str,format="%y-%m-%d %H:%M:%S",tz="US/Pacific") # RESULT # date_local # [1] "2017-06-08 13:09:00 PDT"

We now have the correct date-time and correct time-zone.