带有负值的 Python timedelta 问题 [英] Python timedelta issue with negative values

查看:44
本文介绍了带有负值的 Python timedelta 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助来理解为什么会发生这种情况.我有一种方法可以跟踪事件程序中的剩余时间":

def get_program_time_budget(self):返回 self.estimated_duration-self.get_program_duration()

当estimated_duration > self.get_program_duration() 时一切正常,但当情况相反时,事情就变得有趣了.

结果显示给用户:

预计 11 小时 已分配 10 小时 55 分钟 剩余 5 分钟

当结果为负时,它会这样做:

预计 11 小时 已分配 11 小时 5 分钟 剩余 -1 天 23 小时 55 分钟

任何想法如何获得结果 -5 分钟?

这是 timedelta 格式化程序(注意这是一个 Django 过滤器,因此接收 timedelta 值作为 str - 但它存储为 timedelta):

def format_duration(value):尝试:delim = ':'toks = value.split(',')小时 = 分钟 = ''d_string = value.count('day') 和 toks[0] 或 ''h, m, s = d_string 和 toks[-1].strip().split(delim) 或 value.split(delim)尝试:小时 = 整数(小时)除了:经过尝试:分钟 = 整数(米)除了:经过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 ''))返回 "%s %s %s" % (d_string, h_string, m_string)除了例外,e:logging.error("format_duration 中的错误 -> %s.持续时间值=%s" % (e, value))返回''v

解决方案

如果您使用的是 Python 2.7 或更高版本,您可以使用 timedelta.total_seconds() 获取时间增量的 float 表示为正或负秒数.

<预><代码>>>>datetime.timedelta(-1, 86100).total_seconds()-300.0

您应该能够很容易地使用它来计算分钟数.

如果您不使用 Python 2.7,则可以使用文档中的以下等效公式:

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

看起来您可能正在使用 timedelta 的默认字符串表示来显示结果,因此我的原始答案可能没有那么有用.我会建议这样的东西来显示结果:

def get_program_time_budget(self):td = self.estimated_duration-self.get_program_duration()如果 td.days <0:返回 '​​-' + str(datetime.timedelta() - td)返回 str(td)

这现在将返回一个字符串而不是 timedelta,对于负的 timedelta,它将在正的 timedelta 前面加上-".

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?

EDIT: 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 

解决方案

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.

这篇关于带有负值的 Python timedelta 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆