Grace
Grace

Reputation: 201

Use strptime to convert time zone in R

An example of my 'date/time' field is:

2020-12-30T03:32:30.000Z

I wish to convert this timezone to "tz = Singapore". When I executed this code,

geodf$time <- strptime(geodf$time, format = "%Y-%m-%dT%H:%M:%OS", tz="Singapore")

the resulting output is:

"2020-12-30 03:32:30 +08"

The only change it made is the additional label at the back (+08). The timing didn't change at all - I need to change the timing to Singapore's, not just add the +08.

What went wrong?

Upvotes: 0

Views: 397

Answers (1)

Ian Campbell
Ian Campbell

Reputation: 24790

The Z in your time indicates the timezone is UTC. One approach is to use an object of class POSIXct and change the timezone:

geodf$time <- as.POSIXct(geodf$time,
                         format = "%Y-%m-%dT%H:%M:%OS", tz="UTC")
geodf
#                 time
#1 2020-12-30 03:32:30

attributes(geodf$time)$tzone <- "Singapore"
geodf
#                 time
#1 2020-12-30 11:32:30

Sample Data:

geodf <- structure(list(time = "2020-12-30T03:32:30.000Z"),
                   class = "data.frame", row.names = c(NA, -1L))

Upvotes: 2

Related Questions