Python 2不同的日期时间秒

时间:2013-02-07 09:54:28

标签: python datetime

from datetime import datetime, date, time
import time

fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.now
time.sleep(5)
d2 = datetime.now
diff = (d2-d1).seconds
print(diff)  

我收到

的错误消息
diff = (d2-d1).seconds
TypeError: unsupported operand type(s) for -: 'builtin_function_or_method' and 'builtin_function_or_method'

如何以秒为单位格式化两个日期时间?

3 个答案:

答案 0 :(得分:0)

()之后,您错过了now括号:

from datetime import datetime, date, time
import time

fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.now()
time.sleep(5)
d2 = datetime.now()
diff = (d2-d1).seconds
print(diff) 

答案 1 :(得分:0)

now是一个函数,所以你试图减去的是两个函数。试试这个: datetime.now() - datetime.now()

答案 2 :(得分:0)

问题是你没有调用datetime.now函数,你只是将d1和d2分配给函数的引用。这应该可以解决您的问题:

d1 = datetime.now() # note the function call
d2 = datetime.now()