给定一个Sys.time()
,我想返回最近的历史星期五的日期时间。
例如,给定下面的Sys.time((:
Sys.time()
[1] "2022-03-23 18:59:26 EDT"
我想要:
"2022-03-18 00:00:00 -03"
(注意,我设置了tz = "Etc/GMT+3"
(
我想要的可能吗?如果是,我可以从哪里开始?
我认为您可以使用POSIXlt
包含工作日(星期一是1
(的事实:
today <- Sys.Date()
dput(as.POSIXlt(today))
# structure(list(sec = 0, min = 0L, hour = 0L, mday = 23L, mon = 2L,
# year = 122L, wday = 3L, yday = 81L, isdst = 0L), class = c("POSIXlt",
# "POSIXt"), tzone = "UTC")
(as.POSIXlt(today)$wday - 5) %% 7
# [1] 5
today - 5
# [1] "2022-03-18"
format(today - 5, format = "%a")
# [1] "Fri"
这适用于POSIXt
对象,而不仅仅是Date
对象:
now <- Sys.time()
(as.POSIXlt(now)$wday - 5) %% 7
# [1] 5