How to round a Timestamp
to the nearest SignedDuration
?
#270
-
What's the easiest way to round a This is what I'm currently doing: let bucket_start = timestamp
.round(
TimestampRound::new()
.smallest(Unit::Nanosecond)
.mode(RoundMode::Trunc)
.increment(bucket_duration.as_nanos().try_into().unwrap()),
)
.unwrap(); I was somewhat expecting to be able to use the mod operator to do this let bucket_start = timestamp - (timestamp % bucket_duration); Another option I've considered: let timestamp_ns = new_timestamp.as_nanosecond();
let bucket_start_ns = timestamp_ns - (timestamp_ns % self.bucket_duration.as_nanos());
let bucket_start = Timestamp::from_nanosecond(bucket_start_ns).unwrap(); |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
You could remove |
Beta Was this translation helpful? Give feedback.
-
What I have now is working just fine, but was a bit unintuitive to find. Adding helper methods to create a TimestampRound::from(bucket_duration).mode(RoundMode::Trunc) |
Beta Was this translation helpful? Give feedback.
But
TimestampRound::from_duration
still has the same problem I cited above. If you doTimestampRound::from_duration(...).smallest(Unit::Microsecond)
, what is its behavior?And note that there are already a number of requirements on what
increment
values are considered legal. An error will occur if you get it wrong. This doesn't quite handle the error case ofsigned_duration.as_nanos() as i64
silently truncating though. But since the increment already has to divide evenly into 86,400 seconds, and 86,400,000,000,000 nanoseconds fits into ani64
, it's hard for me to reason about exactly what could go wrong here.In any case,
as
is a footgun unto itself. I'm not sure I want to be adding APIs …