static_rtti
static_rtti

Reputation: 56362

Compute the time since the beginning of the week?

I have a bunch of datetime data and I'd like to see if there is any weekly pattern in it. So I'd like to compute the elapsed time (in seconds) since the beginning of the week with R.

How can I do that? I did the same thing for a daily pattern using difftime(time,as.Date(time)) but I can't use the same trick for the week as there is no as.Week().

Upvotes: 5

Views: 357

Answers (2)

Dirk is no longer here
Dirk is no longer here

Reputation: 368609

You can do it in base R, and you already gave yourself the answer: difftime() with a proper offset.

Even midnight is good enough as you simply need to add dayOfTheWeek * 24 * 60 * 60 to is, and dayOfTheWeek is a field in POSIXlt.

If you want higher-end helper packages, my RcppBDT has a few functions from Boost Date_Time too.

Illustration:

R> now <- Sys.time()
R> midnight <- trunc(now, "days")   # elegant way to get midnight; thanks @flodel
R> today <- as.POSIXlt(Sys.Date())
R> today$wday   # it is Sunday
[1] 0
R> 
R> difftime(now, midnight, unit="secs")
Time difference of 56630.6 secs
R> 

So you could add today$wday * 24 * 60 * 60

R> as.numeric(difftime(now, midnight, unit="secs")) + today$wday*24*60*60
[1] 56630.6
R> 

Upvotes: 7

Theodore Lytras
Theodore Lytras

Reputation: 3963

Here's my solution as well:

secs.in.week <- function(t) {
  d <- as.integer(format(t, "%w"))
  d <- ifelse(d, d-1, 6)
  weekstart <- as.POSIXct(as.Date(t)-d) - 2 * 3600  # Convert UTC -> Local time. I'm on UTC+2h
  as.numeric(difftime(t,weekstart), units="secs")
}

Upvotes: 3

Related Questions