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()
.
Here are the steps needed to calculate the number of weeks between two dates. Divide the number of days by 7 and round down. You will get the number of full weeks. Calculate the integer remainder after dividing the number of days by 7.
The formula for calculating elapsed time is elapsed time = end time – start time. Subtract the minutes and hours separately. For example to calculate the elapsed time between 12:10 and 16:40, subtract 12:10 from 16:4. Looking at the hours, 16 – 12 = 4 and looking at the minutes, 40 – 10 = 30.
To calculate the number of weeks between two dates, start by counting the number of days between the start and end date. Then, divide that number by 7 days per week.
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>
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With