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

Thomas Bulka thom@@@tb@bu|k@ @end|ng |rom gm@||@com
Sun Jun 6 13:00:07 CEST 2021


Am Sa., 5. Juni 2021 um 11:47 Uhr schrieb Micha Silver <tsvibar using gmail.com>:
> 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",
> strftime(Sys.time(),"%Y-%m-%dT%H:%M:%S%z"))
> my_dates
> [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)
> my_dates2
> [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...

Hi Micha,

thank you very much for your detailed reply. In fact, I probably have
not been too clear about my intentions, but you somehow managed to
tell me everything I wanted to know... Your solution works perfectly
for me!

Thanks again and kind regards,

Thomas



More information about the R-help mailing list