Skip to content
Prev 397029 / 398500 Next

Time zones in POSIClt objects

?s 15:13 de 10/10/2024, Jeff Newmiller via R-help escreveu:
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