Thanks all for your comments and solutions!

Best regards,
Iago

________________________________
De: Ivan Krylov <ikry...@disroot.org>
Enviat el: dijous, 22 d��agost de 2024 11:27
Per a: Iago Gin�� V��zquez <iago.g...@sjd.es>
A/c: r-help@r-project.org <r-help@r-project.org>
Tema: Re: [R] Force conversion of (POSIXct) time zone with base R

�� Thu, 22 Aug 2024 08:59:46 +0000
Iago Gin�� V��zquez <iago.g...@sjd.es> ��ڧ�֧�:

> How should POSIXct time zone be changed without modifying the
> specified time (so fix the time zone).

Since POSIXct represents the number of seconds since the specified
"epoch" moment (beginning of 1970 UTC), fixing the time zone while
retaining the local time requires modifying the stored time.

It might be easier to go through POSIXlt, which represents a local time:

(now <- as.POSIXlt(Sys.time()))
attr(now, 'tzone') <- 'UTC'
(now <- as.POSIXct(now))

(Why attr(now, 'tzone') and not now$zone? Historical reasons, I
suppose, but at least both are documented in ?POSIXlt.)

You might also go through the string representation (which effectively
obtains the local time from the epoch time), but that feels brittle,
especially if the POSIXct value has attr(., 'tzone') set:

# time zone information successfully lost and replaced by UTC
Sys.time() |> format() |> as.POSIXct(tz = 'UTC')

--
Best regards,
Ivan

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to