Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute the time since the beginning of the week?

Tags:

r

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().

like image 608
static_rtti Avatar asked Jan 13 '13 21:01

static_rtti


People also ask

How do you calculate time in weeks?

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.

How do you calculate time between start and end time?

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.

How do you calculate weeks from start date?

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.


2 Answers

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> 
like image 107
Dirk Eddelbuettel Avatar answered Sep 18 '22 15:09

Dirk Eddelbuettel


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")
}
like image 32
Theodore Lytras Avatar answered Sep 21 '22 15:09

Theodore Lytras