Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python timedelta issue with negative values

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):     return self.estimated_duration-self.get_program_duration()  

All fine when the estimated_duration > self.get_program_duration() but when this goes the other way things get funny.

Results are displayed to the user:

Estimated   11 hours    Allocated       10 hours 55 minutes     Remaining       5 minutes 

When the result goes negative it does this:

Estimated   11 hours    Allocated       11 hours 5 minutes  Remaining       -1 day 23 hours 55 minutes 

Any ideas how to get the result -5 minutes?

Here is the timedelta formatter (Note this is a Django filter, so receives the timedelta value as a str - but it is stored as a timedelta):

def format_duration(value):   try:     delim = ':'     toks = value.split(',')     hour = minute = ''     d_string = value.count('day') and toks[0] or ''     h, m, s = d_string and toks[-1].strip().split(delim) or value.split(delim)     try:         hour = int(h)     except:         pass     try:         minute = int(m)     except:         pass       h_string = "%s%s%s" % (hour and hour or '', (hour and ' hour' or ''),(hour and hour > 1 and 's' or '')  )     m_string = "%s%s%s" % (minute and minute or '', (minute and ' minute' or ''),(minute and minute > 1 and 's' or ''))     return "%s %s %s" % (d_string, h_string, m_string)   except Exception, e:     logging.error("Error in format_duration -> %s. Duration value=%s" % (e, value))     return ''v  
like image 590
Drew Nichols Avatar asked Dec 06 '11 23:12

Drew Nichols


People also ask

Can Timedelta be negative Python?

They can be both positive and negative. Timedelta is a subclass of datetime.

Is Timedelta always positive?

In timedelta() object delta represents the difference between two dates or times. All the arguments are optional and are 0 by default. We can pass both positive and negative values in the arguments.

How does Python compare to Timedelta?

You can also find the difference between two datetime objects to get a timedelta object and perform the comparison based on the positive or negative value returned by the timedelta. total_seconds() function. if seconds < 0: print('First date is less than the second date.

What is the use of Timedelta () function in Python?

timedelta() function. Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations.


1 Answers

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.

like image 67
Andrew Clark Avatar answered Sep 17 '22 00:09

Andrew Clark