Skip to content

Instantly share code, notes, and snippets.

@treyhunner
Last active May 20, 2020 01:47
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save treyhunner/6218526 to your computer and use it in GitHub Desktop.
Save treyhunner/6218526 to your computer and use it in GitHub Desktop.
Python modulo support for datetime
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]

>>> 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)

@mscheper
Copy link

mscheper commented Apr 8, 2017

I love the internet. Thank you, this is exactly what I need.

@mscheper
Copy link

mscheper commented Apr 8, 2017

... well, not quite. I've created a fork that preserves timezone awareness. I'm not sure if it's possible, but if you'd like me to try to create a pull request for you, let me know.

@thehesiod
Copy link

@jtlz2
Copy link

jtlz2 commented May 14, 2018

Ditto, spot on, and timely - thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment