-
-
Notifications
You must be signed in to change notification settings - Fork 291
Description
An issue I've ran into at work where I'm working with a lot of data primary keyed by timestamps is the need to group data that are equal up to some level of precision. For example, I may need to crate a HashMap using DateTimes, and I need to ensure that DateTimes that have the same date and hour, regardless of minute or second or millisecond, are keyed identically in that map. As it stands right now there's no ergonomic way to do this, and the halfway ergonomic ways (using `.replace_minute(), .replace_second(), etc., one by one) all have the chance to produce errors. Truncation is a 100% safe operation and should be available without having to worry about possible errors. Since the operations are safe, you can technically just unwrap the result, but in many use-cases (such as mine), there can be no linking to the panic handler in production code.
There is a workaround, but it's pretty ugly. It works like the following:
dt.replace_time(time!(00:00:00)).saturating_add(Duration::hours(dt.hour().into()))Having a suite of infallible truncation methods would be nice (.truncate_day(), .truncate_hour(), .truncate_minute(), etc)! Additionally, the solution for a safe truncation combined with a saturating add would also mean there could be an infallible suite of saturating rounding operations, which would be a huge ergonomics boost for the library (.saturating_round_hour(), etc.) which would work on using the truncation method and then doing a saturating add of the unit you're rounding to.
I'm willing to do the work to implement these if the maintainers think this would be something they'd want to merge!