[R] Force conversion of (POSIXct) time zone with base R

Iago Giné Vázquez |@go@g|ne @end|ng |rom @jd@e@
Thu Aug 22 11:33:47 CEST 2024


Thanks all for your comments and solutions!

Best regards,
Iago

________________________________
De: Ivan Krylov <ikrylov using disroot.org>
Enviat el: dijous, 22 d��agost de 2024 11:27
Per a: Iago Gin�� V��zquez <iago.gine using sjd.es>
A/c: r-help using r-project.org <r-help using 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.gine using 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]]



More information about the R-help mailing list