Search code examples
pythonpython-2.7integer-overflowtimedelta

python Timedelta overflow


I am trying to return a timedelta but when time_value is too large it overflows and gives an error. I can use a check to see if time_value is too large but I would prefer a wrapper that handles the error and returns a default. I have included the code for what I'm doing right now. Is there a version of timedelta or datetime that will do this for me?

def time_format(time_value):
            try:
                if time_value is None:
                    return 0
                elif time_value > 0:
                    return (timedelta(seconds=-time_value))
            except OverflowError:
                return 0

Solution

  • You could use datetime.timedelta.min and datetime.timedelta.max. Note that these two are not symmetric about 0.

    Then your code becomes

    time_offset = 0
    if timedelta.min.total_seconds() <= -time_value <= timedelta.max.total_seconds():
        time_offset = timedelta(seconds=-time_value)