cantordust
cantordust

Reputation: 33

Formatting Timezone part of DateTime object in R

Is there a way to extract the timezone or format the timezone part of a datetime object, in the form of, say "+530" instead of "IST" or "Asia/Kolkata"?

(Need this as it is the ISO 8601 format used in javascript)

Example:

as.POSIXct(1499773898,tz="Asia/Kolkata",origin="1970-01-01")
[1] "2017-07-11 17:21:38 IST"

Instead, I'd like to maybe specify the format argument in as.POSIXct, so that the output looks something like this:

[1] "2017-07-11 17:21:38 +530"

Or a function which can pull out the timezone offset in this manner:

timezone_offset("2017-07-11 17:21:38 IST")
[1] "+530"

Does lubridate or any other package have the capability to do this?

Upvotes: 2

Views: 2356

Answers (1)

Chris Holbrook
Chris Holbrook

Reputation: 2636

You can do both with format, but note that result is character string, no longer POSIXct object.

x <- as.POSIXct(1499773898,tz="Asia/Kolkata",origin="1970-01-01")

"2017-07-11 17:21:38 IST"

e.g., Show timestamp in ISO 8601:

format(x, "%Y-%m-%dT%H:%M:%S%z")

"2017-07-11T17:21:38+0530"

e.g., Show just offset from UTC:

format(x, "%z")

"+0530"

Note that for operations in R this has little consequence because all POSIXct objects are stored internally as numeric in UTC; seconds from 1970-01-01 00:00:00.

To write POSIXct timestamps in ISO 8601 to file, you can use format as described above or fwrite function in data.table, which does so by default (see dateTimeAs argument).

Upvotes: 2

Related Questions