timedelta 对象在 Python 2.7 中有一个 total_seconds 方法。所以你可以用它来解决它。当您从另一个日期时间对象中减去一个日期时间对象时,您会得到一个 timedelta 对象。
from datetime import timedelta
minutes = 60
hours = 60 * minutes
days = 24 * hours
diff = timedelta(days=6)
days_in_the_past = int(diff.total_seconds() / days)
hours_remainder = diff.total_seconds() % days
hours_in_the_past = int(diff.total_seconds() / hours)
seconds_remainder = diff.total_seconds() % hours
这就是你想做的吗?如果您使用的是旧版本的 Python,那么您可以定义一个与 total_seconds 方法执行相同操作的函数,如下所示:
def total_seconds(timedelta_object):
return timedelta_object.days * 86400 + timedelta_object.seconds