Skip to content

Instantly share code, notes, and snippets.

@admackin
Created April 26, 2012 05:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save admackin/2496132 to your computer and use it in GitHub Desktop.
Save admackin/2496132 to your computer and use it in GitHub Desktop.
TimeDeltaCustom - adds functionality to Python timedelta objects
from datetime import timedelta
class TimeDeltaCustom(timedelta):
"""A variant of timedelta with some neat extra features.
In particular, it supports division of TimeDeltaCustom by TimeDeltaCustom,
float multiplication, and getting the total number of seconds or hours.
"""
@classmethod
def from_delta(cls, orig_delta):
return cls(orig_delta.days, orig_delta.seconds, orig_delta.microseconds)
def __truediv__(self, other):
if hasattr(self, 'total_seconds') and hasattr(other, 'total_seconds'):
return self.total_seconds() / other.total_seconds()
res = super(TimeDeltaCustom, self).__div__(other)
if isinstance(res, timedelta):
res = TimeDeltaCustom.from_delta(res)
return res
def __div__(self, other):
return self.__truediv__(other)
def total_seconds(self):
return (self.microseconds + (self.seconds + self.days * 24 * 3600) * 1e6) / 1e6
def total_hours(self):
return self.total_seconds() / 3600
def total_days(self):
return self.total_hours() / 24
def __add__(self, other):
res = super(TimeDeltaCustom, self).__add__(other)
if isinstance(res, timedelta):
res = TimeDeltaCustom.from_delta(res)
return res
def __sub__(self, other):
res = super(TimeDeltaCustom, self).__sub__(other)
if isinstance(res, timedelta):
res = TimeDeltaCustom.from_delta(res)
return res
def __mul__(self, other):
if isinstance(other, float):
return TimeDeltaCustom(seconds=other * self.total_seconds())
res = super(TimeDeltaCustom, self).__mul__(other)
if isinstance(res, timedelta):
res = TimeDeltaCustom.from_delta(res)
return res
def __rmul__(self, other):
return self.__mul__(other)
def __abs__(self):
res = super(TimeDeltaCustom, self).__abs__()
if isinstance(res, timedelta):
res = TimeDeltaCustom.from_delta(res)
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment