r-lib / clock

A Date-Time Library for R
https://clock.r-lib.org
Other
97 stars 4 forks source link

Return of `as.POSIXct(<clock_sys_time>)` lacks time zone #367

Closed eitsupi closed 4 months ago

eitsupi commented 4 months ago

IIUC, clock_sys_time should be interpreted as UTC, but there is no time zone information in the return value of as.POSIXct(<clock_sys_time>), which is exactly the same value as for clock_naive_time.

DavisVaughan commented 4 months ago

That's not quite right. clock_sys_time can be thought of as UTC if you want, which means that when you convert to POSIXct it can be translated into any timezone.

For consistency with pretty much every other as.POSIXct() method, it converts it to tz = "" by default, so your local timezone.

For clock_naive_time, that doesn't have an implied timezone yet. It still tries to convert to tz = "" in the as.POSIXct() method, but that will instead retain the clock time (i.e. like you just smacked the time zone on to whatever time was being shown before, without changing that time).

library(clock)

# Interpret as UTC
x <- time_point_cast(sys_time_now(), "second")
x
#> <sys_time<second>[1]>
#> [1] "2024-02-29T14:29:02"

# Shown in local time zone, mine is America/New_York
as.POSIXct(x)
#> [1] "2024-02-29 09:29:02 EST"

as.POSIXct(x, tz = "UTC")
#> [1] "2024-02-29 14:29:02 UTC"

# Strip off any implied time zone
x <- as_naive_time(x)
x
#> <naive_time<second>[1]>
#> [1] "2024-02-29T14:29:02"

# Now, no matter what time zone you convert to, it will try and retain
# the clock time (note that this isn't always possible!)
as.POSIXct(x)
#> [1] "2024-02-29 14:29:02 EST"
as.POSIXct(x, tz = "UTC")
#> [1] "2024-02-29 14:29:02 UTC"

Created on 2024-02-29 with reprex v2.0.2

eitsupi commented 4 months ago

Oh I see, I understand. Thank you for your immediate response!