【问题标题】:alternative to total_seconds() in python 2.6在 python 2.6 中替代 total_seconds()
【发布时间】:2015-03-21 06:59:14
【问题描述】:

在 python 2.7 中有 total_seconds() 方法。

在python 2.6中不存在,建议使用

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

有人可以告诉我如何在下面实现它吗?

谢谢

import datetime

timestamp = '2014-10-24 00:00:00'
timestamp = int((datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S') - datetime.datetime(1970,1,1)).total_seconds())
print timestamp

timestamp = '2014-10-24 00:00:00'
timestamp = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S') - datetime.datetime(1970,1,1)
print timestamp

【问题讨论】:

  • 使用文档提供的内容有什么问题?
  • 不确定问题出在哪里 - 也许您混淆了时间戳和时间增量?在你的程序运行之后,变量timestamp 实际上包含了一个timedelta 对象。如果您将其命名为 td,则上面给出的公式会产生预期的结果。
  • 您错过了文档告诉您该公式要求启用真正的除法,例如from __future__ import division。或者将一个或另一个操作数转换为浮点数(例如,通过除以10.0**6 显式或隐式)。

标签: python time


【解决方案1】:

这是一个 timedelta_total_seconds 函数,使用 2.7 可以看到它与使用 total_seconds 方法获得相同的输出。

import datetime


def timedelta_total_seconds(timedelta):
    return (
        timedelta.microseconds + 0.0 +
        (timedelta.seconds + timedelta.days * 24 * 3600) * 10 ** 6) / 10 ** 6


timestamp = '2014-10-24 00:00:00'
time_delta = datetime.datetime.strptime(
    timestamp, '%Y-%m-%d %H:%M:%S') - datetime.datetime(1970, 1, 1)

print timedelta_total_seconds(time_delta)
print time_delta.total_seconds()

输出

1414108800.0
1414108800.0

【讨论】:

  • 一旦您遵循文档并启用真正的除法from __future__ import division+ 0.0 就是多余的。
猜你喜欢
  • 1970-01-01
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-30
  • 2010-12-16
  • 2012-06-24
  • 2017-01-17
相关资源
最近更新 更多