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

Ivan Krylov |kry|ov @end|ng |rom d|@root@org
Thu Aug 22 11:27:30 CEST 2024


В 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



More information about the R-help mailing list