>>> from datetime_modulo import datetime
>>> from datetime import timedelta
>>> d = datetime.now()
>>> d
datetime(2016, 4, 15, 18, 16, 37, 684181)
>>> d % timedelta(seconds=60)
datetime.timedelta(0, 37, 684181)
>>> d // timedelta(seconds=60)
datetime.datetime(2016, 4, 15, 18, 16)
>>> d % timedelta(minutes=15)
datetime.timedelta(0, 97, 684181)
>>> d // timedelta(minutes=15)
datetime.datetime(2016, 4, 15, 18, 15)
-
-
Save mscheper/9c39091e12f2ca8addb3d5eef7a40480 to your computer and use it in GitHub Desktop.
Python modulo support for datetime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime as dt | |
class datetime(dt.datetime): | |
"""The standard datetime class with the added support for the % and // | |
operators. | |
Refer to https://gist.github.com/treyhunner/6218526 | |
""" | |
def __divmod__(self, delta): | |
seconds = int((self - dt.datetime.min.replace(tzinfo = self.tzinfo)).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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment