user2205916
user2205916

Reputation: 3456

R: given Sys.Date(), find date-time of most recent, historical, Friday

Given a Sys.time(), I want to return the date-time of the most recent, historical Friday.

For example, given the Sys.time() below:

Sys.time()
[1] "2022-03-23 18:59:26 EDT"

I want:

"2022-03-18 00:00:00 -03"

(Notice that I set tz = "Etc/GMT+3")

Is what I want possible? If so, where might I start?

Upvotes: 1

Views: 116

Answers (1)

r2evans
r2evans

Reputation: 160942

I think you can use the fact that POSIXlt contains the weekday (Monday is 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"

This works identically with POSIXt objects, not just Date objects:

now <- Sys.time()
(as.POSIXlt(now)$wday - 5) %% 7
# [1] 5

Upvotes: 2

Related Questions