【发布时间】: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显式或隐式)。