Search code examples
rtimeutcstrptimezone

Converting UTC Time to Local Time with Days of Week and Date Included


I have the following 2 columns as part of a larger data frame. The Timezone_Offset is the difference in hours for the local time (US West Coast in the data I'm looking at). In other words, UTC + Offset = Local Time.

I'm looking to convert the UTC time to the local time, while also correctly changing the day of the week and date, if necessary. For instance, here are the first 5 rows of the two columns.

                           UTC              Timezone_Offset
Sun Apr 08 02:42:03 +0000 2012                           -7
Sun Jul 01 03:27:20 +0000 2012                           -7
Wed Jul 11 04:40:18 +0000 2012                           -7
Sat Nov 17 01:31:36 +0000 2012                           -8
Sun Apr 08 20:50:30 +0000 2012                           -7

Things get tricky when the day of the week and date also have to be changed. For instance, looking at the first row, the local time should be Sat Apr 07 19:42:03 +0000 2012. In the second row, the month also has to be changed.

Sorry, I'm fairly new to R. Could someone possibly explain how to do this? Thank you so much in advance.


Solution

  • Parse as UTC, then apply the offset in seconds, ie times 60*60 :

    data <- read.csv(text="UTC,       Timezone_Offset
    Sun Apr 08 02:42:03 +0000 2012,                    -7
    Sun Jul 01 03:27:20 +0000 2012,                    -7
    Wed Jul 11 04:40:18 +0000 2012,                    -7
    Sat Nov 17 01:31:36 +0000 2012,                    -8
    Sun Apr 08 20:50:30 +0000 2012,                    -7", stringsAsFactors=FALSE)
    
    data$pt <- as.POSIXct(strptime(data$UTC, "%a %b %d %H:%M:%S %z %Y", tz="UTC"))
    
    data$local <- data$pt + data$Timezone_Offset*60*60
    

    Result:

    > data[,3:4]
                       pt               local
    1 2012-04-08 02:42:03 2012-04-07 19:42:03
    2 2012-07-01 03:27:20 2012-06-30 20:27:20
    3 2012-07-11 04:40:18 2012-07-10 21:40:18
    4 2012-11-17 01:31:36 2012-11-16 17:31:36
    5 2012-04-08 20:50:30 2012-04-08 13:50:30
    >