[R] Conversion of String to Datetime: How to Keep Timezone Offset when Printing?

Micha Silver t@v|b@r @end|ng |rom gm@||@com
Sat Jun 5 11:47:21 CEST 2021

On 6/4/21 9:20 PM, Thomas Bulka wrote:
> Hello list,
> I do have a hard time handling date and time data with different
> timezone offsets. Say, I have two strings which represent different
> dates/times, like so:
> DT1 <- "2021-06-19T13:45:00-03:00"
> DT2 <- "2020-07-20T11:39:12+02:00"
> my_dates <- c(DT1, DT2)
> What I want to do now, is to covert those strings into some kind of
> datetime object which allows for comparisons (earlier/later etc.).
> Using as_datetime from the lubridate package seems to do the trick,
> but it converts DT1 and DT2 with reference to UTC. I guess, this makes
> sense from a computational point of view, since, most likely, this is
> how R internally handles dates and times.
> However, I would like to be able to at least visually distinguish the
> different timezone offsets, if the data is printed. I'm able to
> manually set a timezone with the tz parameter of as_datetime:

It's not clear what you're asking. The time strings already have the 
timezone offset specified. If you get rid of the "T" character in the 
strings, then you can use regular datetime formatting specifiers to 
convert to R datetime objects, i.e.

my_dates = c("2021-06-19T13:45:00-03:00", "2020-07-20T11:39:12+02:00", 
[1] "2021-06-19T13:45:00-03:00" "2020-07-20T11:39:12+02:00"
[3] "2021-06-05T12:33:11+0300"
my_dates2 = gsub(pattern="T", replacement=" ", x=my_dates)
[1] "2021-06-19 13:45:00-03:00" "2020-07-20 11:39:12+02:00"
[3] "2021-06-05 12:33:11+0300"

# Now convert to datetime objects, including TZ offset:

my_datetimes = as.POSIXct(my_dates2, "%Y-%m-%d %H:%M:%S%z")

# And these datetimes you can visualize any way you want:

strftime(my_datetimes, format="%d/%b/%Y %H:%M %Z", tz="EST")
[1] "19/Jun/2021 08:45 EST" "20/Jul/2020 06:39 EST" "05/Jun/2021 07:33 EST"

Not sure if that helps at all...

> as_datetime(DT1, tz = "EDT")
> [1] "2020-07-20 09:39:12 EDT"
> But this only works if I enter the timezone manually.
> So what I want to ask is this: Is there any possibility, to convert
> all entries of a vector my_dates (see above) into datetime objects
> while keeping a visual indication of each timezone offset when the
> data is printed?
> Please excuse any awkward phrasing; being pretty new to R, I probably
> did not phrase anything correctly.
> Thank you very much in advance!
> Thomas
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

Micha Silver
Ben Gurion Univ.
Sde Boker, Remote Sensing Lab
cell: +972-523-665918

More information about the R-help mailing list