What would be an elegant, efficient and Pythonic way to perform a h/m/s rounding operation on time related types in Python with control over the rounding resolution?
My guess is that it would require a time modulo operation. Illustrative examples:
- 20:11:13 % (10 seconds) => (3 seconds)
- 20:11:13 % (10 minutes) => (1 minutes and 13 seconds)
Relevant time related types I can think of:
datetime.datetime
\datetime.time
struct_time
For a datetime.datetime rounding, see this function: https://stackoverflow.com/a/10854034/1431079
Sample of use:
This will round up time data to a resolution as asked in the question:
I think I'd convert the time in seconds, and use standard modulo operation from that point.
20:11:13 =
20*3600 + 11*60 + 13
= 72673 seconds72673 % 10 = 3
72673 % (10*60) = 73
This is the easiest solution I can think about.
Here is a lossy* version of hourly rounding:
Same principle can be applied to different time spans.
*The above method assumes UTC is used, as any timezone information will be destroyed in conversion to timestamp.
I use following code snippet to round to the next hour: