[R] Time zones in POSIClt objects

Jan van der Laan rhe|p @end|ng |rom eoo@@dd@@n|
Fri Oct 11 13:24:35 CEST 2024


On 10/11/24 11:56, Rui Barradas wrote:
> Hello,
>
> A way to have different time zones is to store t1 and t2 in list, 
> which are vectors. Just not atomic vectors.
> I think it complicates what should be simple, but here it is.
>
>
>
> # create two lists
> t1 <- lapply(c("2024-01-01 12:30", "2024-01-01 12:30"), as.POSIXlt, tz 
> = "GMT")
> t2 <- lapply(c("2024-01-01 12:30", "2024-01-01 12:30"), as.POSIXlt, tz 
> = "CET")
>
> # this works but is it a wanted way of making simple computations?
> Map(`-`, t1, t2)
> #> [[1]]
> #> Time difference of 1 hours
> #>
> #> [[2]]
> #> Time difference of 1 hours
>
> # mapply default is to simplify the result, if possible
> mapply(`-`, t1, t2)
> #> [1] 1 1
>
> t1 <- lapply(c("2024-01-01 12:30", "2024-01-01 12:30"), as.POSIXlt, tz 
> = "GMT")
> t2 <- lapply(c("2024-01-01 12:30", "2024-01-01 12:30"), as.POSIXlt, tz 
> = "CET")
>
> # as documented in ?mapply > sapply, all attributes are lost,
> # after simplification the class attribute follows the hierarchy
> # NULL < raw < logical < integer < double < complex < character < list 
> < expression
> mapply(`-`, t1, t2) |> str()
> #>  num [1:2] 1 1
>
>
> # now change only one member of the list t1
> attr(t1[[2]], "tzone") <- attr(t2[[2]], "tzone")
>
> # t1 has two different time zones and the Map/mapply loops
> # above still give the expected results
> Map(`-`, t1, t2)
> #> [[1]]
> #> Time difference of 1 hours
> #>
> #> [[2]]
> #> Time difference of 0 secs
>
> mapply(`-`, t1, t2)
> #> [1] 1 0
>
>
> Hope this helps,
>
> Rui Barradas


Thanks. That would basically mean writing a separate class for date-time 
objects. If it was for a specific application where it is important to 
keep the time zones, this might be a good solution. However, the dates 
are output from a generic package and I would like to output something 
that is practical for users. Such a list of dates as you are proposing 
would not be supported by a lot of existing packages. Even something 
like plotting with the dates on the x-axis would not work. Perhaps a 
POSIXct object with an extra attribute containing the time zones would 
then be easier: by default everything would then be in, for example, UTC.

As I mentioned in the previous mail, I currently have a solution that 
converts everything to local time. But that means loosing the individual 
time zone information.

Best,

Jan



More information about the R-help mailing list