CapnShanty
CapnShanty

Reputation: 559

How to get as.POSIXct to not change timezone of string?

This has been causing me problems for a while. I have a column of date-time strings like this:

"2016-09-13 22:27:37.320 UTC"

And I have been trying to get them coerced into POSIXct objects using:

library(anytime)
final$contact <- as.POSIXct(anytime(final$contact, tz="UTC"))

But it gives me the time as if I'd converted it from my local timezone (EST) to UTC, despite my inclusion of UTC in the string, then specifying in anytime that the tz is UTC:

2016-09-14 02:27:37

The ultimate end-goal of this is to pass them into this:

for (i in 1:NROW(final$first_rpc)){
    final$localcontact[i] <- format(final$contact[i],
                                    tz=as.character(final$timezone.x[i]),
                                    usetz = TRUE)
}

So that each time uses its respective timezone instead of UTC (which is how the data is stored in our database).

This is about the fourth version of this I've tried and I really have no idea how to make it work the way I'd like, where the string up there is converted into as POSIXct object still in UTC. Is there any way to make anytime/as.POSIXct realize that these are in UTC already?

Upvotes: 1

Views: 1086

Answers (3)

IRTFM
IRTFM

Reputation: 263481

I think you need to include both the usetz and tz parameters to get as.POSIXct to honor the UTC designation. The %z and %Z formats are for output only:

as.POSIXct(x, format = "%Y-%m-%d %H:%M:%S", usetz=TRUE, tz="UTC")
#[1] "2016-09-13 22:27:37 UTC"

`anytime (from package by the same name) uses different parameter names:

anytime::anytime(x, asUTC=TRUE)
[1] "2016-09-13 15:27:37 PDT"  # value came in as UTC but the default print output is local
anytime::anytime(x, asUTC=TRUE, tz="UTC")  # overrides local tz conversion
[1] "2016-09-13 22:27:37 UTC"

Like your unnamed database (perhaps homegrown) R stores all date-time objects as UTC and it's only at output that a timezone designator is applied. If you have a mixture of timezones coming in then yu will need to preprocess them and store the associated source TZ as character values before sending to strptime or as.POSIXct, as you are already anticipating.

Upvotes: 2

akrun
akrun

Reputation: 887891

We don't need to specify the format here as it is already in the Date Time format

as.POSIXct(str1, tz = "UTC")
#[1] "2016-09-13 22:27:37 EDT"

data

str1 <- "2016-09-13 22:27:37.320 UTC"

Upvotes: 2

12b345b6b78
12b345b6b78

Reputation: 1015

x <- "2016-09-13 22:27:37.320 UTC"
as.POSIXct(x, format = "%Y-%m-%d %H:%M:%S", tz ='EST')
[1] "2016-09-13 22:27:37 EST"

Upvotes: 1

Related Questions