我在转换一些字符时遇到一个小问题(格式是CET,它们只是存储为字符)。我想将格式从字符更改为日期,以便我可以在时区之间进行转换。这是我正在查看的一小部分数据。
timestamps <- c("2023-10-29 00:00:00", "2023-10-29 00:15:00", "2023-10-29 00:30:00", "2023-10-29 00:45:00", "2023-10-29 01:00:00", "2023-10-29 01:15:00", "2023-10-29 01:30:00", "2023-10-29 01:45:00", "2023-10-29 02:00:00", "2023-10-29 02:15:00", "2023-10-29 02:30:00", "2023-10-29 02:45:00", "2023-10-29 03:00:00", "2023-10-29 02:15:00", "2023-10-29 02:30:00", "2023-10-29 02:45:00", "2023-10-29 03:00:00", "2023-10-29 03:15:00", "2023-10-29 03:30:00", "2023-10-29 03:45:00", "2023-10-29 04:00:00", "2023-10-29 04:15:00")
我的第一次尝试是执行以下操作:
as.POSIXct(timestamps, tz = "CET")
但这给出了以下输出:
[1] "2023-10-29 00:00:00 CEST" "2023-10-29 00:15:00 CEST" "2023-10-29 00:30:00 CEST" "2023-10-29 00:45:00 CEST" "2023-10-29 01:00:00 CEST"
[6] "2023-10-29 01:15:00 CEST" "2023-10-29 01:30:00 CEST" "2023-10-29 01:45:00 CEST" "2023-10-29 02:00:00 CEST" "2023-10-29 02:15:00 CET"
[11] "2023-10-29 02:30:00 CET" "2023-10-29 02:45:00 CET" "2023-10-29 03:00:00 CET" "2023-10-29 02:15:00 CET" "2023-10-29 02:30:00 CET"
[16] "2023-10-29 02:45:00 CET" "2023-10-29 03:00:00 CET" "2023-10-29 03:15:00 CET" "2023-10-29 03:30:00 CET" "2023-10-29 03:45:00 CET"
[21] "2023-10-29 04:00:00 CET" "2023-10-29 04:15:00 CET"
此处 CEST 时区未正确分配。它们应该分配到“2023-10-29 03:00:00”时间戳。
我还尝试使用 lubridate 中的“ymd_hms”,但这也没有成功:
[1] "2023-10-29 00:00:00 CEST" "2023-10-29 00:15:00 CEST" "2023-10-29 00:30:00 CEST" "2023-10-29 00:45:00 CEST" "2023-10-29 01:00:00 CEST"
[6] "2023-10-29 01:15:00 CEST" "2023-10-29 01:30:00 CEST" "2023-10-29 01:45:00 CEST" "2023-10-29 02:00:00 CET" "2023-10-29 02:15:00 CET"
[11] "2023-10-29 02:30:00 CET" "2023-10-29 02:45:00 CET" "2023-10-29 03:00:00 CET" "2023-10-29 02:15:00 CET" "2023-10-29 02:30:00 CET"
[16] "2023-10-29 02:45:00 CET" "2023-10-29 03:00:00 CET" "2023-10-29 03:15:00 CET" "2023-10-29 03:30:00 CET" "2023-10-29 03:45:00 CET"
[21] "2023-10-29 04:00:00 CET" "2023-10-29 04:15:00 CET"
实际上,与以前相比,现在分配给“CEST”时区的时间段减少了 1 个时间段。 有没有人有办法解决这个问题?
如果您假设数据已排序,则可以为 (
+0100
) duplicated
次添加 CET
,为 +0200
次添加 CEST
,然后在 %z
调用中添加 as.POSIXct
。
ifelse(duplicated(timestamps) | as.POSIXct(timestamps, tz = "CET") > as.POSIXct("2023-10-29 03:00:00"),
paste0(timestamps, " +0100"),
paste0(timestamps, " +0200")
) |>
as.POSIXct(format="%Y-%m-%d %H:%M:%S %z")
给予:
[1] "2023-10-29 00:00:00 CEST" "2023-10-29 00:15:00 CEST" "2023-10-29 00:30:00 CEST" "2023-10-29 00:45:00 CEST" "2023-10-29 01:00:00 CEST" "2023-10-29 01:15:00 CEST"
[7] "2023-10-29 01:30:00 CEST" "2023-10-29 01:45:00 CEST" "2023-10-29 02:00:00 CEST" "2023-10-29 02:15:00 CEST" "2023-10-29 02:30:00 CEST" "2023-10-29 02:45:00 CEST"
[13] "2023-10-29 02:00:00 CET" "2023-10-29 02:15:00 CET" "2023-10-29 02:30:00 CET" "2023-10-29 02:45:00 CET" "2023-10-29 03:00:00 CET" "2023-10-29 03:15:00 CET"
[19] "2023-10-29 03:30:00 CET" "2023-10-29 03:45:00 CET" "2023-10-29 04:00:00 CET" "2023-10-29 04:15:00 CET"