简体   繁体   中英

Calculate time to or from a fixed hour of the day

I have a bunch of timestamps in R:

set.seed(42)  
t <- sample(1368104620:1399593658, 1000)
t <- as.POSIXlt(t, origin="1970-01-01")

I want to know how far each timestamp is from a fixed hour of the day (eg how far is the timestamp from 5am? [either 5am today, yesterday, or tomorrow]). The max distance should be 12.

h <- t$hour + t$min/60 + t$sec/3600
h_fixed <- 5

One method for doing this is to compare the current hour to the fixed_hour, the fixed_hour yesterday, and the fixed_hour today.

d1 <- pmin(abs(h-h_fixed),abs(h-h_fixed+24),abs(h-h_fixed-24))
plot(h, d1)

Another, slightly fancier approach is as follows:

d2 <- pmin((h_fixed-h) %% 24, (h-h_fixed) %% 24)
plot(h, d2)
all.equal(d1, d2)

Is their a more elegant approach? I feel like I should be able to solve this without using pmin, but the answer eludes me.

Another solution uses the fact that the max distance is 12:

d3 <- ifelse(abs(h-h_fixed)<12, abs(h-h_fixed), 24-(abs(h-h_fixed)))
all.equal(d1, d3)

So if the time is within 12 hours of fixed_hour today, that's our answer. If it's not, then it's the 'complement' of our desired answer. Since we're only interested in distance, it doesn't really matter if the time is closer to yesterday or tomorrow. Not sure if this is more elegant, but it does solve the problem without using pmin() .

Not clear if this is better or worse but this formula seems to work and it is concise:

dif <- abs(h - h_fixed)
12 - abs(dif - 12)

It can also be written as one line:

12 - abs(abs(h - h_fixed) - 12)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM