【问题标题】:using total_seconds function in python 2.6在 python 2.6 中使用 total_seconds 函数
【发布时间】:2017-12-18 20:56:47
【问题描述】:

我有一个场景,我需要使用total_seconds() 方法,但在 python 2.7 中没有运行相同的选项。在 python 2.6 total_seconds() 方法不存在。

建议使用

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

任何人都可以在这里帮助我,我如何在下面的代码中使用它。 或者任何替代方案都会很棒。

   final = self.stats['FINAL']
    self.stats['START'] = start = final[0][1]
    self.stats['END'] = end = final[-1][2]
    self.stats['DELTA'] = delta = end - start
    self.stats['IS_AVAILABLE'] = is_available = final[-1][0]

    self.stats['AVAILABLE'] = {}
    self.stats['AVAILABLE'][True] = {}
    self.stats['AVAILABLE'][False] = {}

    for entry in final:
        is_available = entry[0]
        dstart = entry[1]
        dend = entry[2]
        edelta = dend - dstart
        etotsec = int(edelta.total_seconds())
        availability[is_available]['last'] = dend
        try:
            # Number of seconds in this status
            seconds = availability[is_available]['seconds']
            seconds = seconds + etotsec
            availability[is_available]['seconds'] = seconds
            self.stats['AVAILABLE'][is_available]['SECONDS'] = seconds

            # Update count
            count = availability[is_available]['count']
            count = count + 1
            availability[is_available]['count'] = count
            self.stats['AVAILABLE'][is_available]['COUNT'] = count
        except:
            availability[is_available]['seconds'] = etotsec
            availability[is_available]['count'] = 1
            self.stats['AVAILABLE'][is_available]['SECONDS'] = etotsec
            self.stats['AVAILABLE'][is_available]['COUNT'] = 1

        try:
            # Register entry
            registry = availability[is_available]['registry']
            registry.append(entry)
            availability[is_available]['registry'] = registry
            self.stats['AVAILABLE'][is_available]['REGISTRY'] = registry
        except:
            availability[is_available]['registry'] = []
            self.stats['AVAILABLE'][is_available]['REGISTRY'] = []

    self.stats['LAST_UP'] = lastup = availability[True]['last']
    self.stats['DOWN_COUNT'] = numdowntime = availability[False]['count']
    self.stats['DOWN_SECONDS'] = totdowntime = availability[False]['seconds']
    self.stats['UP_COUNT'] = numuptime = availability[True]['count']
    self.stats['UP_SECONDS'] = totuptime = availability[True]['seconds']

    self.stats['DOWN_PERCENTAJE'] = ptotdowntime = totdowntime * 100 / delta.total_seconds()
    self.stats['UP_PERCENTAJE'] = ptotuptime = totuptime * 100 / delta.total_seconds()
    self.stats['DOWN_LIST'] = downtimes = availability[False]['registry']
    downtimes.reverse()

    REPORT += "First entry recorded: %s\n" % start
    REPORT += " Last entry recorded: %s\n" % end
    REPORT += "        Is Available: %s\n" % is_available
    if not is_available:
        REPORT += "        Last time up: %s\n" % lastup
    REPORT += "        SAP Lifetime: %s\n" % delta
    REPORT += "         Unavailable: %s, %d times down, %.02f%% of lifetime\n" % (str(timedelta(seconds=availability[False]['seconds'])), numdowntime, ptotdowntime)
    REPORT += "           Available: %s, %.02f%% of lifetime\n\n" % (str(timedelta(seconds=availability[True]['seconds'])), ptotuptime)
    REPORT += "Last %d/%d downtimes:\n" % (self.props['SHOW_MAX_DOWNTIMES'], len(downtimes))

    for n in range(len(downtimes)):
        if n < self.props['SHOW_MAX_DOWNTIMES']:
            start = downtimes[n][1]
            end = downtimes[n][2]
            delta = end - start
            duration = str(timedelta(seconds=delta.total_seconds()))
            REPORT += "\t%2d - Down from: %s\t\tto: %s\tDuration: %s\n" % (n + 1, downtimes[n][1], downtimes[n][2], duration)

【问题讨论】:

    标签: python python-2.7 python-2.6 timedelta python-datetime


    【解决方案1】:

    只需将该公式放入函数中,并使用函数而不是方法:

    from __future__ import division
    
    def td_total_seconds(td):
        # note that this relies on true division being enabled with 
        # from __future__ import division.
        # alternatively, replace the 10**6 divisor with 10.0**6 or insert `0.0 +`
        # at the front, or explicitly convert either operand with float()
        return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
    

    这是直接等价的:

    >>> timedelta(days=1, seconds=255423, microseconds=12345).total_seconds()
    341823.012345
    >>> td_total_seconds(timedelta(days=1, seconds=255423, microseconds=12345))
    341823.012345
    

    然后,无论何时使用object.total_seconds(),您都使用td_total_seconds(object)。您发布的代码中的一些示例;原行

    etotsec = int(edelta.total_seconds())
    

    变成

    etotsec = int(td_total_seconds(edelta))
    

    其他行变成:

    self.stats['DOWN_PERCENTAJE'] = ptotdowntime = totdowntime * 100 / td_total_seconds(delta)
    self.stats['UP_PERCENTAJE'] = ptotuptime = totuptime * 100 / td_total_seconds(delta)
    

    最后一个例子看起来像是重构的遗留物?它没有多大意义,它只创建一个timedelta 对象的副本,然后将该对象转换为字符串。您可以直接将对象转换为字符串,无需复制。您可以在下一行将字符串转换为 printf 样式的字符串格式:

    REPORT += "\t%2d - Down from: %s\t\tto: %s\tDuration: %s\n" % (n + 1, downtimes[n][1], downtimes[n][2], (end - start))
    

    这消除了前面的 delta =duration = 行的需要。

    【讨论】:

    猜你喜欢
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多