Skip to content

Instantly share code, notes, and snippets.

@mscheper
Forked from treyhunner/datetime_modulo.py
Last active July 29, 2024 15:27
Show Gist options
  • Save mscheper/9c39091e12f2ca8addb3d5eef7a40480 to your computer and use it in GitHub Desktop.
Save mscheper/9c39091e12f2ca8addb3d5eef7a40480 to your computer and use it in GitHub Desktop.
Python modulo support for datetime
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]
>>> 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment