2

I have a series of datetime.time data, and I want to apply modulo operation on it, converting all data into some intervals.

For example, using a 5-minute interval, datetime.time(11, 38, 27, 785327) will be converted to datetime.time(11, 35, 0, 0)

How can I accomplish this sort of rounding?

cmaher
  • 5,100
  • 1
  • 22
  • 34
Ziqi Liu
  • 2,931
  • 5
  • 31
  • 64
  • check out this question: https://stackoverflow.com/questions/3463930/how-to-round-the-minute-of-a-datetime-object-python/10854034#10854034 – Nathan Feb 11 '18 at 16:56

2 Answers2

1
input_time = datetime.time(11, 38, 27, 785327)
mod_time = datetime.time(input_time.hour, input_time.minute//5*5)
codingatty
  • 2,026
  • 1
  • 23
  • 32
1

Came across this execellent solution

https://gist.github.com/treyhunner/6218526

import datetime as dt


class datetime(dt.datetime):
    def __divmod__(self, delta):
        seconds = int((self - dt.datetime.min).total_seconds())
        remainder = dt.timedelta(
            seconds=seconds % delta.total_seconds(),
            microseconds=self.microsecond,
        )
        quotient = self - remainder
        return quotient, remainder

    def __floordiv__(self, delta):
        return divmod(self, delta)[0]

    def __mod__(self, delta):
        return divmod(self, delta)[1]
SolessChong
  • 3,370
  • 8
  • 40
  • 67