Python timedelta issue with negative values

前端 未结 2 2027
独厮守ぢ
独厮守ぢ 2020-11-28 11:00

Hi I need some help to understand why this is happening. I have a method to track \'time remaining\' in an event program:

def get_program_time_budget(self):
         


        
相关标签:
2条回答
  • 2020-11-28 11:34

    Why?

    Possibly as a unintended side effect of the way // and % are defined.

    Possibly because it makes it easier to implement the datetime class. Five minutes before the epoch is 23:55, not 0:-5.

    It doesn't really matter. Just know that it's how days, seconds, and microseconds get normalized. And that it can easily be worked around.

    def format_timedelta(td):
        if td < timedelta(0):
            return '-' + format_timedelta(-td)
        else:
            # Change this to format positive timedeltas the way you want
            return str(td)
    
     >>> format_timedelta(timedelta(minutes=-5))
     '-0:05:00'
    
    0 讨论(0)
  • 2020-11-28 11:35

    If you are using Python 2.7 or higher you can use timedelta.total_seconds() to get a float representation of the timedelta as a positive or negative number of seconds.

    >>> datetime.timedelta(-1, 86100).total_seconds()
    -300.0
    

    You should be able to use this to calculate a number of minutes fairly easily.

    If you are not using Python 2.7 you can use the following equivalent formula from the docs:

    (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10.0**6
    

    Edit: It looks like you are probably using the default string representation for timedelta to display the result, so my original answer may not be as useful. I would suggest something like this for displaying the result:

    def get_program_time_budget(self):
        td = self.estimated_duration-self.get_program_duration()
        if td.days < 0:
            return '-' + str(datetime.timedelta() - td)
        return str(td)
    

    This would now return a string instead of a timedelta, and for negative timedeltas it would prepend a '-' to a positive timedelta.

    0 讨论(0)
提交回复
热议问题